﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Reflection;
using System.Security;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.ViewModels;
using GKQC.Machine;
using GKQC.DbHelper.Services;
using GKQC.Common;
using System.Linq;
using SqlSugar;
using System.IO;
using GKQC.Ort.Reports;
using System.Threading.Tasks;
using GKQC.DbHelper.ErpDbModels;
using GKQC.DbHelper.ErpViewModels;
using System.Text.RegularExpressions;
using GKQC.Language;
using NPOI.SS.UserModel;
using System.Runtime.InteropServices;
using GKQC.Forms;
using ComponentFactory.LcrMes.Toolkit.QControls;
using NPOI.SS.Formula.Functions;
using System.Security.Policy;

namespace GKQC.Ort
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FormOrt : QcFormBase
    {
        UserModel _User = null;
        AllDbContext dbContext = null;
        //OrtViewModel ortViewModel = null;
        FormStatus _FormStatus = FormStatus.Browser;
        OrtHeadModel _CurrentHead = null;
        OrtDtlModel _CurrentDtl;
        List<OrtHeadModel> _Heads = null;
        OrtService _OrtService = null;
        List<ReportSetModel> _ReportSetModels;
        string _BillType = string.Empty;
        int _MaxRowCount = 100;
        List<ElectricViewModel> _EmptyElectricViews = new List<ElectricViewModel>();
        List<SizeViewModel> _EmptySizeViews = new List<SizeViewModel>();
        List<OrtDtlModel> _EmptyDtlModels = new List<OrtDtlModel>();
        List<int> _LockIds = new List<int>();
        FormOrtFilter _FormFilter;
        readonly string _DefaultDateFomat = "yyyy-MM-dd";
        List<ItemCodeTran> _ItemCodeTrans = new List<ItemCodeTran>();
        List<BaseDataModel> _BillTypes = new List<BaseDataModel>();
        ///// <summary>
        ///// ERP检测标准缓存
        ///// </summary>
        //Dictionary<string, List<qcd_view>> qcdDic = new Dictionary<string, List<qcd_view>>();
        ListSortDirection MainSort = ListSortDirection.Descending;
        bool isAutoGenReport = false;//保存自動導出EXCEL報表到系統參數【OutPath】指定的文件夾

        public FormOrt(UserModel userMode, AllDbContext dbContext, string billType)
        {
            InitializeComponent();

            try
            {
                //Stopwatch sp = new Stopwatch();
                //StringBuilder sb = new StringBuilder();
                //sp.Start();
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                SubFormList = new List<Form>();
                _FormStatus = FormStatus.Browser;
                _BillType = billType;
                BillType = billType;
                txtBillType.Text = billType;
                if (billType == "FQC")
                    splitContainer1.Panel2Collapsed = true;
                //tssbillTypeDesc.Text = GetBillTypeDesc() + " "  + billType;
                //this.Text = tssbillTypeDesc.Text;
                this._User = userMode;
                this.tssUser.Text = this._User.UserName;
                this.dbContext = dbContext;
                ItemCodeTranService.GetItemCodeTran(dbContext, _ItemCodeTrans);
                _OrtService = new OrtService(dbContext);
                var ipqcservice = new BaseDataTypeService(dbContext);
                var billTypes = ipqcservice.GetUseDatas("ORT");
                if (billTypes != null && billTypes.Count > 0)
                    this._BillTypes.AddRange(billTypes);
                GetReportSet();
                FormCommon.SetLevel(cboLevel);
                FormCommon.SetSourceCode(cboSourceCode);
                GetFreqlSet();
                FormCommon.SetTestTarget(cboTestTarget);
                MainDataGridView.AutoGenerateColumns = false;
                DtlDataGridView.AutoGenerateColumns = false;
                ElectricDataGridView.AutoGenerateColumns = false;
                VDataGridView.AutoGenerateColumns = false;
                //SizeDataGridView.AutoGenerateColumns = false;
                this.ElectricDataGridView.RowPostPaint += DataGridViewSet.RowPostPaint;
                //this.SizeDataGridView.RowPostPaint += DataGridViewSet.RowPostPaint;
                this.MainDataGridView.RowPostPaint += DataGridViewSet.RowPostPaint;
                //this.DtlDataGridView.RowPostPaint += DataGridViewSet.RowPostPaint;
                this.ElectricDataGridView.CellFormatting +=
                     new System.Windows.Forms.DataGridViewCellFormattingEventHandler(DataGridViewSet.CellFormatting);
                this.ElectricDataGridView.CellFormatting +=
                     new System.Windows.Forms.DataGridViewCellFormattingEventHandler(DataGridViewSet.CellFormattingForColor);// CellFormattingStrikeout
                //this.SizeDataGridView.CellFormatting +=
                //    new System.Windows.Forms.DataGridViewCellFormattingEventHandler(DataGridViewSet.CellFormatting);
                //this.SizeDataGridView.CellFormatting +=
                //    new System.Windows.Forms.DataGridViewCellFormattingEventHandler(DataGridViewSet.CellFormattingForColor);

                ColReportId.DataPropertyName = "";
                ColReportId.DataSource = new BindingList<ReportSetModel>(_ReportSetModels);
                ColReportId.ValueType = typeof(ReportSetModel);
                ColReportId.DisplayMember = "Name";
                ColReportId.ValueMember = "Id";
                ColReportId.DataPropertyName = "ReportId";

                MainDataGridView.RowEnter += MainDataGridView_RowEnter;
                DtlDataGridView.RowEnter += DtlDataGridView_RowEnter;

                txtCap.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtVoltage.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtDfMax.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtDfMaxAfter.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtLcMax.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtLcMaxAfter.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtZMax.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtEsrMax.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtEsrMaxAfter.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtTestTemp.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtRipperCurrent.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtCap.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtVoltage.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtDfMax.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtDfMaxAfter.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtLcMax.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtLcMaxAfter.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtZMax.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtEsrMax.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtEsrMaxAfter.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtTestTemp.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtRipperCurrent.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);

                txtLcTime.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtLcTime.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);

                txtDMax.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtDMax.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtLMax.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtLMax.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);
                txtFMax.GotFocus += new EventHandler(FormCommon.TextBox_GotFocus);
                txtFMax.MouseUp += new MouseEventHandler(FormCommon.TextBox_MouseUp);

                if (this._BillType == "S" || this._BillType == "Y")
                {
                    ColReportId.DisplayIndex = 1;
                    ColReportId.Frozen = true;
                }

                
                txtSize.LostFocus += TxtSize_LostFocus;
                dteTestDate.LostFocus += DteTestDate_LostFocus;
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                BindingData();
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                tabControl.SelectedTab = tabMain;
                MainDataGridView.Focus();
                if (_Heads != null && _Heads.Count > 0)
                    MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(0, 0));
                else
                    _CurrentHead = new OrtHeadModel();
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                BindingControls();
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                SetControlsEnable();
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                //Logger.LogMessage(sb.ToString());
                LanguageHelper.SetControlLanguageText(this);
                IsAutoGenReport();

                DataGridViewColumnStyle.GetColumnStyle(this._User.UserCode, this.Name, MainDataGridView);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0017", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GetReportSet()
        {
            try
            {
                //这里不要做多语言转换
                _ReportSetModels = _ReportSetModels = ReportDbService.GetReports(dbContext, "信賴性試驗檢測單");
                if (_ReportSetModels != null)
                {
                    cboReport.DisplayMember = "Name";
                    cboReport.ValueMember = "Id";
                    cboReport.DataSource = _ReportSetModels;
                }

                cboBillType.DisplayMember = "GroupAndName";
                cboBillType.ValueMember = "Code";
                cboBillType.DataSource = _BillTypes;
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0020", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化頻率下拉框
        /// </summary>
        private void GetFreqlSet()
        {
            try
            {
                Dictionary<string, string> soure = new Dictionary<string, string>();
                soure.Add("120Hz", "120Hz");
                soure.Add("100KHz", "100KHz");
                soure.Add("1KHz", "1KHz");
                soure.Add("10KHz", "10KHz");

                BindingSource bs = new BindingSource();
                bs.DataSource = soure;

                cboTestFreq.DisplayMember = "Key";
                cboTestFreq.ValueMember = "Value";
                cboTestFreq.DataSource = bs;
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0038", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Hide();
            this.Close();
        }

        #region 工具栏
        private void tsmLcr_Double_Click(object sender, EventArgs e)
        {
            //if (!BeforeTest()) return;
            try
            {
                if (MachineFactory.ExistsTestForm(TestType.Lcr, SubFormList)) return;

                if (MainDataGridView.SelectedRows != null && MainDataGridView.SelectedRows.Count > 2)
                {
                    QMessageBox.Show("一次最多选两张单据进行测试，当前选中单据数为：" + MainDataGridView.SelectedRows.Count.ToString()
                        , "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                int firstSNo =1;
                OrtHeadModel firstHead = null;

                if (MainDataGridView.SelectedRows != null && MainDataGridView.SelectedRows.Count > 0)
                {
                    firstHead = MainDataGridView.SelectedRows[MainDataGridView.SelectedRows.Count -1]
                        .DataBoundItem as OrtHeadModel;
                }
                if (firstHead == null)
                    firstHead = _CurrentHead;
                if (firstHead == null) return;
                if (firstHead.Dtls.Count == 0) firstHead.Dtls = _OrtService.GetDtls(firstHead.Id);
                if (firstHead.Dtls.Count>0)
                    firstSNo = firstHead.Dtls.Max(t=>t.SNo);

                if(!string.IsNullOrWhiteSpace(firstHead.ApproveUser))
                {
                    QMessageBox.Show("第一单号" + firstHead.BillNo + "已审核，不能再修改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //检查单据是否被锁定
                string msg = string.Empty;
                LockModel lockModel = LockService.GetLockModel(dbContext, this, firstHead.Id.ToString(), out msg);
                if (lockModel != null && lockModel.Id > 0)
                {
                    QMessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                FormTranData f = new FormTranData(firstHead, firstSNo
                    , _User, _BillType, _ReportSetModels
                    , _OrtService
                    );
                f.SetDoubleTestLabel();

                OrtHeadModel secondHead = null;
                OrtDtlModel secondDtl;
                int secondSNo = 1;
                if (MainDataGridView.SelectedRows != null && MainDataGridView.SelectedRows.Count >1)
                {
                    secondHead = MainDataGridView.SelectedRows[MainDataGridView.SelectedRows.Count - 2]
                        .DataBoundItem as OrtHeadModel;
                    if (secondHead != null)
                    {
                        if (secondHead.Dtls.Count == 0)
                            secondHead.Dtls = _OrtService.GetDtls(secondHead.Id);

                        if (secondHead.Dtls.Count > 0)
                            secondSNo = secondHead.Dtls.Max(t => t.SNo);

                        f.SetTargetBill(secondHead.BillNo, secondSNo);
                    }
                }

                if (f.ShowDialog() != DialogResult.OK) return;

                string firstBillNo = f.SourceBillNo;
                firstSNo = f.SourceSNo;
                string secondBillNo = f.TargetBillNo;
                secondSNo = f.TargetSNo;


                if (string.IsNullOrWhiteSpace(firstBillNo))
                {
                    QMessageBox.Show("第一单号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (firstSNo <= 0)
                {
                    QMessageBox.Show("第一次数必须大于0", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (string.IsNullOrWhiteSpace(secondBillNo))
                {
                    QMessageBox.Show("第二单号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (secondSNo <= 0)
                {
                    QMessageBox.Show("第二次数必须大于0", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (firstBillNo == secondBillNo)
                {
                    QMessageBox.Show("第一单号与第二单号不能相同", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (firstBillNo == _CurrentHead.BillNo)
                    firstHead = _CurrentHead;
                else if (_Heads.Where(t => t.BillNo == firstBillNo).Any())
                    firstHead = _Heads.Where(t => t.BillNo == firstBillNo).First();
                else
                    firstHead = _OrtService.GetHeadByBillNo(firstBillNo);
                if (firstHead == null || firstHead.Id <= 0)
                {
                    QMessageBox.Show("第一单号不存在; " + firstBillNo, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (firstHead.Dtls.Count == 0) firstHead.Dtls = _OrtService.GetDtls(firstHead.Id);
                OrtDtlModel firstDtl = firstHead.Dtls.Where(t => t.SNo == firstSNo).FirstOrDefault();
                if (firstDtl == null)
                {
                    QMessageBox.Show("第一次数不存在; " + firstSNo.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    firstDtl.Datas = _OrtService.GetDatas(firstDtl.HeadId, firstDtl.SNo);
                }
                ViewModelTrans<OrtDataModel>.DataToView(firstDtl.SNo, firstDtl.Datas
                    , firstDtl.ElectricViewModels, firstDtl.SizeViewModels);
                firstDtl.GenerateList(firstHead.ElectricQty, firstHead.ElectricQty, firstDtl.SNo);
                firstDtl.ElectricViewModels.ForEach(t => t.HeadId = firstHead.Id);


                secondHead = _Heads.Where(t => t.BillNo == secondBillNo).FirstOrDefault();
                if(secondHead == null)
                    secondHead = _OrtService.GetHeadByBillNo(secondBillNo);
                if (secondHead == null || secondHead.Id <= 0)
                {
                    QMessageBox.Show("第二单号不存在; " + secondBillNo, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (!string.IsNullOrWhiteSpace(secondHead.ApproveUser))
                {
                    QMessageBox.Show("第二单号" + secondHead.BillNo + "已审核，不能再修改！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //检查单据是否被锁定
                lockModel = LockService.GetLockModel(dbContext, this, secondHead.Id.ToString(), out msg);
                if (lockModel != null && lockModel.Id > 0)
                {
                    QMessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (secondHead.Dtls.Count == 0) secondHead.Dtls = _OrtService.GetDtls(secondHead.Id);
                secondDtl = secondHead.Dtls.Where(t => t.SNo == secondSNo).FirstOrDefault();
                if (secondDtl == null)
                {
                    QMessageBox.Show("第二次数不存在; " + secondSNo.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    secondDtl.Datas = _OrtService.GetDatas(secondDtl.HeadId, secondDtl.SNo);
                }
                ViewModelTrans<OrtDataModel>.DataToView(secondDtl.SNo, secondDtl.Datas
                    , secondDtl.ElectricViewModels, secondDtl.SizeViewModels);
                secondDtl.GenerateList(secondHead.ElectricQty, secondHead.ElectricQty, secondDtl.SNo);
                secondDtl.ElectricViewModels.ForEach(t => t.HeadId = secondHead.Id);
                ReportSetModel secondReport = _ReportSetModels.Where(r => r.Id == secondHead.ReportId).FirstOrDefault();
                _OrtService.GenStandard(secondHead, secondDtl, secondReport?.Code);


                List<ElectricViewModel> testView = new List<ElectricViewModel>();
                testView.AddRange(firstDtl.ElectricViewModels);
                testView.AddRange(secondDtl.ElectricViewModels);

                ReportSetModel firstReport = _ReportSetModels.Where(r => r.Id == firstHead.ReportId).FirstOrDefault();
                //if (cboReport.SelectedItem != null)
                //    report = cboReport.SelectedItem as ReportSetModel;
                var lcrForm = MachineFactory.GetLcrForm(this, _User, firstHead.Voltage, testView, firstHead.Standard
                    , firstReport);

                PropertyInfo p = lcrForm.GetType().GetProperty("SecondStandardView");
                if (p != null)
                {
                    p.SetValue(lcrForm, secondHead.Standard,null);
                }

                p = lcrForm.GetType().GetProperty("IsDoubleTest");
                if (p != null)
                {
                    p.SetValue(lcrForm, true, null);
                }

                p = lcrForm.GetType().GetProperty("FirstDtl_MinSNo");
                if (p != null && firstSNo>1 && firstHead.Dtls.Count>0)
                {
                    OrtDtlModel dtl = firstHead.Dtls[0];
                    if(dtl != firstDtl)
                    {
                        if(dtl.Datas.Count ==0)
                        {
                            dtl.Datas = _OrtService.GetDatas(dtl.HeadId, dtl.SNo);
                            ViewModelTrans<OrtDataModel>.DataToView(dtl.SNo, dtl.Datas
                                , dtl.ElectricViewModels, dtl.SizeViewModels);
                            dtl.GenerateList(firstHead.ElectricQty, firstHead.ElectricQty, dtl.SNo);
                        }
                    }
                    p.SetValue(lcrForm, dtl, null);
                }
                p = lcrForm.GetType().GetProperty("SecondDtl_MinSNo");
                if (p != null && secondSNo > 1 && secondHead.Dtls.Count>0)
                {
                    OrtDtlModel dtl = secondHead.Dtls[0];
                    if (dtl != firstDtl)
                    {
                        if (dtl.Datas.Count == 0)
                        {
                            dtl.Datas = _OrtService.GetDatas(dtl.HeadId, dtl.SNo);
                            ViewModelTrans<OrtDataModel>.DataToView(dtl.SNo, dtl.Datas
                                , dtl.ElectricViewModels, dtl.SizeViewModels);
                            dtl.GenerateList(secondHead.ElectricQty, secondHead.ElectricQty, dtl.SNo);
                        }
                    }
                    p.SetValue(lcrForm, dtl, null);
                }

                //FirstSNo
                p = lcrForm.GetType().GetProperty("FirstSNo");
                if (p != null)
                {
                    p.SetValue(lcrForm, firstSNo, null);
                }

                //SecondSNo
                p = lcrForm.GetType().GetProperty("SecondSNo");
                if (p != null)
                {
                    p.SetValue(lcrForm, secondSNo, null);
                }

                p = lcrForm.GetType().GetProperty("FirstCapRate");
                if (p != null)
                {
                    p.SetValue(lcrForm, firstHead.CapRate, null);
                }

                p = lcrForm.GetType().GetProperty("SecondCapRate");
                if (p != null)
                {
                    p.SetValue(lcrForm, secondHead.CapRate, null);
                }

                //SetFirstLotBackgroup
                var v = lcrForm.GetType().GetMethod("SetFirstLotBackgroup");
                if (v != null)
                    v.Invoke(lcrForm, null);


                    if (lcrForm == null) return;
                var lcrQcForm = lcrForm as QcFormBase;
                if (lcrQcForm != null)
                {

                    lcrQcForm.SetTitle(_CurrentHead.BillNo);
                    //lcrQcForm.Version = this.Version;
                    lcrQcForm.ChargeTime = 120;
                    lcrQcForm.SetTestItem("CD-LC");
                    lcrQcForm.IsDoubleTest = true;
                }

                MethodInfo m = lcrForm.GetType().GetMethod("SetErrorDataFormat");
                if (m != null)
                {
                    m.Invoke(lcrForm, new object[] { false });
                }

                _LockIds.Add(LockService.Lock(dbContext, this._User, this, firstHead.Id.ToString(), firstHead.BillNo));
                _LockIds.Add(LockService.Lock(dbContext, this._User, this, secondHead.Id.ToString(), secondHead.BillNo));

                //Form f = lcrForm as Form;
                lcrQcForm.Show();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0024", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void tsmLcrTest_Click(object sender, EventArgs e)
        {
            if (!BeforeTest()) return;
            try
            {
                if (MachineFactory.ExistsTestForm(TestType.Lcr, SubFormList)) return;

                ReportSetModel report = _ReportSetModels.Where(r => r.Id == _CurrentHead.ReportId).FirstOrDefault();
                //if (cboReport.SelectedItem != null)
                //    report = cboReport.SelectedItem as ReportSetModel;
                var lcrForm = MachineFactory.GetLcrForm(this, _User, _CurrentHead.Voltage, _CurrentDtl.ElectricViewModels, _CurrentHead.Standard
                    , report);

                if (lcrForm == null) return;
                var lcrQcForm = lcrForm as QcFormBase;
                if(lcrQcForm != null)
                {
                    lcrQcForm.SetTitle(_CurrentHead.BillNo);
                    //lcrQcForm.Version = this.Version;
                    lcrQcForm.ChargeTime = 120;
                    lcrQcForm.SetTestItem("CD-LC");
                }

                MethodInfo m = lcrForm.GetType().GetMethod("SetErrorDataFormat");
                if(m != null)
                {
                    m.Invoke(lcrForm, new object[] { false });
                }

                PropertyInfo p = lcrForm.GetType().GetProperty("FirstSNo");
                if (p != null)
                {
                    p.SetValue(lcrForm, _CurrentDtl.SNo, null);
                }

                p = lcrForm.GetType().GetProperty("FirstDtl_MinSNo");
                if (p != null && _CurrentDtl.SNo > 1 && _CurrentHead.Dtls.Count > 0)
                {
                    OrtDtlModel dtl = _CurrentHead.Dtls[0];
                    if (dtl != _CurrentDtl)
                    {
                        if (dtl.Datas.Count == 0)
                        {
                            dtl.Datas = _OrtService.GetDatas(dtl.HeadId, dtl.SNo);
                            ViewModelTrans<OrtDataModel>.DataToView(dtl.SNo, dtl.Datas
                                , dtl.ElectricViewModels, dtl.SizeViewModels);
                            dtl.GenerateList(_CurrentHead.ElectricQty, _CurrentHead.ElectricQty, dtl.SNo);
                        }
                    }
                    p.SetValue(lcrForm, dtl, null);
                }

                p = lcrForm.GetType().GetProperty("FirstCapRate");
                if (p != null)
                {
                    p.SetValue(lcrForm, _CurrentHead.CapRate, null);
                }


                //Form f = lcrForm as Form;
                lcrQcForm.Show();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0024", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmLcTest_Click(object sender, EventArgs e)
        {
            if (!BeforeTest()) return;

            try
            {
                if (MachineFactory.ExistsTestForm(TestType.Lc, SubFormList)) return;

                ReportSetModel report = _ReportSetModels.Where(r => r.Id == _CurrentHead.ReportId).FirstOrDefault();
                //if (cboReport.SelectedItem != null)
                //    report = cboReport.SelectedItem as ReportSetModel;
                var lcForm = MachineFactory.GetLcForm(this, _User, _CurrentHead.Voltage, _CurrentDtl.ElectricViewModels, _CurrentHead.Standard
                    , report);
                if (lcForm == null) return;
                var lcQcForm = lcForm as QcFormBase;
                if (lcQcForm != null)
                {
                    lcQcForm.SetTitle(_CurrentHead.BillNo);
                    lcQcForm.ChargeTime = 120;
                }
                Form f = lcForm as Form;
                f.Show();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0042", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //FormLC2311 f= new FormLC2311(txtVoltage.Text, )
        }

        private void tsmSizeTest_Click(object sender, EventArgs e)
        {
            if (!BeforeTest()) return;

            try
            {
                if (MachineFactory.ExistsTestForm(TestType.Size, SubFormList)) return;

                //FormCaliper f = new FormCaliper(this, _User, _CurrentDtl.SizeViewModels, _CurrentHead.Standard);
                FormCaliper_Ort f = new FormCaliper_Ort(this, _User, _CurrentDtl.ElectricViewModels, _CurrentHead.Standard);
                var lcrQcForm = f as QcFormBase;
                if (lcrQcForm != null)
                {
                    lcrQcForm.SetTitle(_CurrentHead.BillNo);
                }

                f.Show();
                SubFormList.Add(f);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0074", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        bool BeforeTest()
        {
            bool flag = false;

            try
            {
                DtlDataGridView.EndEdit();
                txtRemark.Focus();

                if(_CurrentHead.Dtls.Count == 0 && _CurrentHead.BillType =="FQC")
                {
                    int count = _CurrentHead.ElectricQty;
                    if (count == 0) _CurrentHead.ElectricQty = 13;
                    var dtl = new OrtDtlModel(count, count, 1, _CurrentHead.Id);
                    dtl.HeadId = _CurrentHead.Id;
                    _CurrentHead.Dtls.Add(dtl);
                    DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                }

                if (_CurrentHead.Dtls.Count == 0)
                {
                    QMessageBox.Show("請先新增檢測次數", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    tabControl.SelectedTab = tabMain;
                    btnAddDtl.Focus();
                    return false;
                }

                if (_CurrentDtl == null)
                {
                    QMessageBox.Show("請先選擇測試次數", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    tabControl.SelectedTab = tabMain;
                    DtlDataGridView.Focus();
                    return false;
                }

                if ((_CurrentHead.ReportId == 0 || cboReport.SelectedIndex == -1) && _CurrentHead.BillType != "FQC")
                {
                    QMessageBox.Show("請先選擇報表模板", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    tabControl.SelectedTab = tabDtl;
                    cboReport.Focus();
                    return false;
                }

                if ((_CurrentDtl.ElectricViewModels.Count == 0 && _CurrentHead.ElectricQty > 0)
                    || (_CurrentDtl.SizeViewModels.Count == 0 && _CurrentHead.SizeQty > 0)
                    )
                {
                    _OrtService.GetDatas(_CurrentDtl.HeadId, _CurrentDtl.SNo);
                    ViewModelTrans<OrtDataModel>.DataToView(_CurrentDtl.SNo, _CurrentDtl.Datas
                        , _CurrentDtl.ElectricViewModels, _CurrentDtl.SizeViewModels);
                }

                string reportCode = GetReportCode(_CurrentHead.ReportId);
                int eqty = _CurrentHead.ElectricQty;
                if (eqty <= 0) eqty = 20;
                int sqty = _CurrentHead.SizeQty;
                if (sqty <= 0) sqty = 10;
                _CurrentDtl.GenerateList(eqty, sqty, _CurrentDtl.SNo);
                ElectricDataGridView.DataSource = new BindingList<ElectricViewModel>(_CurrentDtl.ElectricViewModels);

                _OrtService.GenStandard(_CurrentHead, _CurrentDtl, reportCode);

                DtlDataGridView.Enabled = false;
                flag = true;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            return flag;
        }

        private void tsmAdd_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Add))
            {
                return;
            }

            try
            {
                if (tabControl.SelectedTab != tabDtl)
                {
                    tabControl.SelectedTab = tabDtl;
                }

                _FormStatus = FormStatus.Add;
                _CurrentHead = new OrtHeadModel();
                _CurrentHead.CreateDate = this._User.GetServerTime();
                _CurrentHead.CreateUser = this._User.UserName;
                _CurrentHead.BillType = this._BillType;
                txtBillNo.Text = string.Empty;

                //For Approval/In - material/test Regular test/For Research
                if (this._BillType == "LDT" || this._BillType == "LDW" || this._BillType == "SFLDW" || this._BillType == "SFLDT")
                    _CurrentHead.TestTarget = "In-material test"; //cboTestTarget.SelectedIndex = 1;
                else if (this._BillType == "SFTC" || this._BillType == "TC" || this._BillType == "YGL" || this._BillType == "SFYGL")
                    _CurrentHead.TestTarget = "Regular test"; //cboTestTarget.SelectedIndex = 2;
                else if (this._BillType == "Y")//特殊试验*研发
                    _CurrentHead.TestTarget = "study test";
                else if (this._BillType == "S") //特殊试验-量产 quantity production test
                    _CurrentHead.TestTarget = "quantity production test";
                else _CurrentHead.TestTarget = "For Approval"; //cboTestTarget.SelectedIndex = 0;
                cboTestTarget.SelectedItem = _CurrentHead.TestTarget;

                if(this._BillType == "LDT" || this._BillType == "SFLDT")
                {
                    DateTime d = this._User.GetServerTime();
                    if (_CurrentHead.TestTarget == "In-material test")
                    {
                        if(this._BillType == "LDT")
                            _CurrentHead.BillNo = "LDW" + d.ToString("yyMMdd") + "001";
                        else if(this._BillType == "SFLDT")
                            _CurrentHead.BillNo = "SFLDW" + d.ToString("yyMMdd") + "001";
                    }
                }

                //默认值
                string defaultValue = Settings.GetDataObjectFile<string>(this.Name);
                if (!string.IsNullOrWhiteSpace(defaultValue))
                {
                    var d = JsonHelper.ToObject<OrtHeadModel>(defaultValue);
                    if (d != null)
                    {
                        _CurrentHead.LcrMeter = d.LcrMeter;
                        _CurrentHead.LcMeter = d.LcMeter;
                        _CurrentHead.TestTemp = d.TestTemp;
                    }
                }

                //默认报表
                SetDefaultReport();

                if (_CurrentHead.BillType == "FQC" && _CurrentHead.ElectricQty <=0) _CurrentHead.ElectricQty = 13;

                txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, true);
                DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                VDataGridView.DataSource = new BindingList<OrtVoltageModel>(_CurrentHead.Volts);
                DtlDataGridView_RowEnter(DtlDataGridView, null);
                _LockIds.Add(LockService.Lock(dbContext, _User, this, _CurrentHead.Id.ToString(), _CurrentHead.BillNo));
                BindingControls();
                SetControlsEnable();
                tssCurrentId.Text = string.Empty;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0022", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增單據時設置默認報表
        /// </summary>
        void SetDefaultReport()
        {
            try
            {
                if (_CurrentHead == null) return;
                OrtBillType billType = (OrtBillType)Enum.Parse(typeof(OrtBillType), _CurrentHead.BillType);
                ReportSetModel r = null;

                switch (_CurrentHead.BillType)
                {
                    case "TS":
                    case "AA":
                    case "AB":
                    case "AC":
                    case "AD":
                    case "AE":
                    case "AG":
                    case "AH":
                    case "AK":
                    case "AL":
                    case "AN":
                    case "AP":
                    case "AR":
                    case "AS":
                    case "AU":
                    case "AW":
                    case "AY":
                    case "BA":
                    case "BC":
                        r = _ReportSetModels.Where(t => t.Code == "R001").FirstOrDefault();
                        break;
                    case "AF":
                    case "AJ":
                    case "AM":
                    case "AQ":
                    case "AT":
                    case "AX":
                        r = _ReportSetModels.Where(t => t.Code == "R002").FirstOrDefault();
                        
                        break;
                    default:
                        r = _ReportSetModels.Where(t => t.Code == "R001").FirstOrDefault();
                        break;
                }

                if (!string.IsNullOrWhiteSpace(Version) && Version.StartsWith("11"))
                    r = _ReportSetModels.Where(t => t.Code == "R109").FirstOrDefault();

                if (r != null)
                {
                    _CurrentHead.ReportId = r.Id;
                    _CurrentHead.ElectricQty = r.ElectricQty;
                    _CurrentHead.SizeQty = r.SizeQty;
                    if (_CurrentHead.SizeQty == 0) _CurrentHead.SizeQty = _CurrentHead.ElectricQty;
                    if (_CurrentHead.ElectricQty == 0) _CurrentHead.ElectricQty = _CurrentHead.SizeQty;
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void tsmCopy_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Add))
            {
                return;
            }
            try
            {
                FormBaseData formBaseData = new FormBaseData(_User, dbContext, "ORT");
                formBaseData.SetSelectForm();
                if (formBaseData.ShowDialog() != DialogResult.OK)
                    return;
                var biltype = formBaseData.SelectedData;

                if (tabControl.SelectedTab != tabDtl)
                {
                    tabControl.SelectedTab = tabDtl;
                }
                _FormStatus = FormStatus.Copy;
                _CurrentHead = _OrtService.Clone(_CurrentHead);
                _CurrentHead.Id = 0;
                _CurrentHead.TestDate = this._User.GetServerTime();
                _CurrentHead.ModiDate = null;
                _CurrentHead.ModiUser = String.Empty;
                _CurrentHead.ApproveDate = null;
                _CurrentHead.ApproveUser = String.Empty;
                _CurrentHead.CreateDate = this._User.GetServerTime();
                _CurrentHead.CreateUser = this._User.UserCode;
                _CurrentHead.TestVoltage = 0;
                DateTime finishdate = DateTime.Now;
                DateTime.TryParse("2099-12-31", out finishdate);
                _CurrentHead.FinishDate = finishdate;

                if (biltype != null) _CurrentHead.BillType = biltype.Code;

                SetDefaultReport();

                _CurrentHead.BillNo = _OrtService.GetBillNo(_CurrentHead, true);
                if (_CurrentHead.Dtls != null && _CurrentHead.Dtls.Count > 0)
                    _CurrentHead.Dtls.Clear();
                if (_CurrentHead.Volts != null && _CurrentHead.Volts.Count > 0)
                    _CurrentHead.Volts.Clear();
                DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                DtlDataGridView_RowEnter(DtlDataGridView, null);
                VDataGridView.DataSource = new BindingList<OrtVoltageModel>(_CurrentHead.Volts);
                //_LockIds.Add(LockService.Lock(dbContext, _User, this, _CurrentHead.Id.ToString(), _CurrentHead.BillNo));
                BindingControls();
                SetControlsEnable();
                tssCurrentId.Text = string.Empty;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0023", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _FormStatus = FormStatus.Browser;
                SetControlsEnable();
            }
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (_CurrentHead == null) return;
                if (_CurrentHead.Id<=0) return;

                if (!UserRightService.CheckRight(this, this._User, RightType.Modi))
                {
                    return;
                }


                string msg = string.Empty;
                LockModel lockModel = LockService.GetLockModel(dbContext, this, _CurrentHead.Id.ToString(), out msg);
                if (lockModel != null && lockModel.Id > 0)
                {
                    QMessageBox.Show(msg, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                //if (tabControl.SelectedTab != tabDtl)
                //{
                //    tabControl.SelectedTab = tabDtl;
                //}

                DtlDataGridView.DataSource = _EmptyDtlModels;
                ElectricDataGridView.DataSource = _EmptyElectricViews;
                //SizeDataGridView.DataSource = _EmptySizeViews;
                _CurrentDtl = null;
                _LockIds.Add(LockService.Lock(dbContext, this._User, this, _CurrentHead.Id.ToString(), _CurrentHead.BillNo));
                int headIndex = _Heads.IndexOf(_CurrentHead);
                _CurrentHead = _OrtService.GetHeadById(_CurrentHead.Id);// dbContext.QcDb.Queryable<OrtHeadModel>().InSingle(_CurrentHead.Id);
                _Heads[headIndex] = _CurrentHead;
                _CurrentHead.Dtls = _OrtService.GetDtls(_CurrentHead.Id);

                _CurrentHead.Volts = _OrtService.GetVolts(_CurrentHead.Id);
                if (_CurrentHead.Volts == null || _CurrentHead.Volts.Count == 0)
                    _CurrentHead.GenVolts();
                VDataGridView.DataSource = new BindingList<OrtVoltageModel>(_CurrentHead.Volts);


                if (_CurrentHead.Dtls != null)
                {
                    foreach (OrtDtlModel dtl in _CurrentHead.Dtls)
                    {
                        dtl.Datas = _OrtService.GetDatas(_CurrentHead, dtl);
                    }
                    DtlDataGridView.DataSource = _CurrentHead.Dtls;
                }

                BindingControls();
                _FormStatus = FormStatus.Edit;
                SetControlsEnable();
                //this.Refresh();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0018", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Delete))
            {
                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;
                List<OrtHeadModel> delList = new List<OrtHeadModel>();
                foreach (DataGridViewRow r in MainDataGridView.SelectedRows)
                {
                    OrtHeadModel model = r.DataBoundItem as OrtHeadModel;
                    if (model != null && string.IsNullOrWhiteSpace(model.ApproveUser))
                    {
                        delList.Add(model);
                    }
                }

                if (delList.Count == 0
                    && _CurrentHead != null
                    && string.IsNullOrWhiteSpace(_CurrentHead.ApproveUser))
                    delList.Add(_CurrentHead);

                if (delList.Count == 0)
                {
                    QMessageBox.Show("沒有可以刪除的數據","提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    if (QMessageBox.Show("數據刪除後無法恢復，請確認是否刪除"
                        , "請確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                        == DialogResult.Cancel)
                        return;

                    string msg = string.Empty;
                    var lockModels = LockService.GetLockModels(dbContext, this, delList.Select(a => a.Id).ToList(), out msg);
                    if (lockModels != null && lockModels.Count() > 0)
                    {
                        LockModel lockmodel = lockModels.First();
                        QMessageBox.Show(string.Format("單據 {0} 已被 {1} 鎖定，無法刪除！"
                            , lockmodel.BillNo, lockmodel.UserName)
                            , "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    int i = _OrtService.Delete(delList);
                    QMessageBox.Show("刪除成功記錄數：" + i.ToString() + "條"
                        , "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (i > 0)
                    {
                        SysLogService.Log(dbContext, this._User, this, tsmDelete.Text
                            , string.Join(",", delList.Select(m => m.BillNo).ToArray())
                            , delList);
                    }
                    BindingData();
                }

                SetControlsEnable();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0019", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void tsmDelDtl_Click(object sender, EventArgs e)
        {
            if (_CurrentDtl == null) return;
            if (_CurrentHead == null) return;
            if (_FormStatus != FormStatus.Browser)
            {
                QMessageBox.Show("修改或新增狀態不能刪除測試次數，請先保存或取消再刪除！"
                    , "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!UserRightService.CheckRight(this, this._User, RightType.Delete))
            {
                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (_CurrentDtl.Datas.Where(t => t.Value > 0).Any()
                    //|| _CurrentDtl.Datas.Where(t => t.Valid.Length > 1).Any()

                    )
                {
                    QMessageBox.Show("测试次数 " + _CurrentDtl.SNo.ToString() + " 有測試值，無法刪除！"
                        ,"提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                {
                    if (QMessageBox.Show("即將刪除測試次數：" 
                        + _CurrentDtl.SNo.ToString() + "，數據刪除後無法恢復，請確認是否刪除"
                        , "請確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                        == DialogResult.Cancel)
                        return;

                    string msg = string.Empty;
                    var lockModels = LockService.GetLockModels(dbContext, this, new List<long>() { _CurrentDtl.HeadId }, out msg);
                    if (lockModels != null && lockModels.Any())
                    {
                        LockModel lockmodel = lockModels.First();
                        QMessageBox.Show(string.Format("單據 {0} 已被 {1} 鎖定，無法刪除測試次數！", lockmodel.BillNo, lockmodel.UserName)
                            , "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    int i = _OrtService.DeleteDtl(_CurrentDtl);
                    QMessageBox.Show("刪除成功記錄數：" + i.ToString() + "條", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (i > 0)
                    {
                        SysLogService.Log(dbContext, this._User, this, tsmDelete.Text + LanguageHelper.GetLanguageText("測試次數")
                            , _CurrentHead.BillNo
                            , _CurrentDtl.ToJson());

                        _CurrentHead.Dtls.Remove(_CurrentDtl);
                        DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                    }
                    BindingData();
                }

                SetControlsEnable();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0019", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void tsmApprove_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Approve))
            {
                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;
                List<OrtHeadModel> approveList = new List<OrtHeadModel>();
                List<int> approveIndexs = new List<int>();
                int currentIndex = 0;
                if (_CurrentHead != null) currentIndex = _Heads.IndexOf(_CurrentHead);
                foreach (DataGridViewRow r in MainDataGridView.SelectedRows)
                {
                    OrtHeadModel model = r.DataBoundItem as OrtHeadModel;
                    if (model != null && string.IsNullOrWhiteSpace(model.ApproveUser))
                    {
                        model.ApproveUser = this._User.UserName;
                        model.ApproveDate = this._User.GetServerTime();
                        approveList.Add(model);
                        approveIndexs.Add(_Heads.IndexOf(model));
                    }
                }

                if (approveList.Count == 0
                    && _CurrentHead != null
                    && string.IsNullOrWhiteSpace(_CurrentHead.ApproveUser))
                {
                    _CurrentHead.ApproveUser = this._User.UserName;
                    _CurrentHead.ApproveDate = this._User.GetServerTime();
                    approveList.Add(_CurrentHead);
                }

                string msg = string.Empty;
                var lockModels = LockService.GetLockModels(dbContext, this, approveList.Select(a => a.Id).ToList(), out msg);
                if (lockModels != null && lockModels.Count() > 0)
                {
                    LockModel lockmodel = lockModels.First();
                    QMessageBox.Show(string.Format("單據 {0} 已被 {1} 鎖定，無法審核！", lockmodel.BillNo, lockmodel.UserName)
                        , "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                if (approveList.Count == 0)
                {
                    QMessageBox.Show("沒有需要審核的數據", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    int i = _OrtService.Approve(approveList);
                    QMessageBox.Show("審核成功記錄數：" + i.ToString() + "條", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (i > 0)
                    {
                        SysLogService.Log(dbContext, this._User, this, tsmApprove.Text
                            , string.Join(",", approveList.Select(m => m.BillNo).ToArray())
                            , string.Empty);
                    }
                    foreach (var idx in approveIndexs)
                    {
                        _Heads[idx] = _OrtService.GetHeadById(_Heads[idx].Id);
                    }
                    MainDataGridView.Refresh();
                    _CurrentHead = _Heads[currentIndex];
                    BindingControls();
                    picApprove.Visible = true;
                }

                SetControlsEnable();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0019", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void tsmUnApprove_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.UnApprove))
            {
                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;
                List<OrtHeadModel> unApproveList = new List<OrtHeadModel>();
                List<int> unApproveIndexs = new List<int>();
                int currentIndex = 0;
                if (_CurrentHead != null) currentIndex = _Heads.IndexOf(_CurrentHead);
                foreach (DataGridViewRow r in MainDataGridView.SelectedRows)
                {
                    OrtHeadModel model = r.DataBoundItem as OrtHeadModel;
                    if (model != null && !string.IsNullOrWhiteSpace(model.ApproveUser))
                    {
                        model.ApproveUser = string.Empty;
                        model.ApproveDate = this._User.GetServerTime();
                        unApproveList.Add(model);
                        unApproveIndexs.Add(_Heads.IndexOf(model));
                    }
                }

                if (unApproveList.Count == 0
                    && _CurrentHead != null
                    && !string.IsNullOrWhiteSpace(_CurrentHead.ApproveUser))
                {
                    _CurrentHead.ApproveUser = string.Empty;
                    _CurrentHead.ApproveDate = this._User.GetServerTime();
                    unApproveList.Add(_CurrentHead);
                }

                if (unApproveList.Count == 0)
                {
                    QMessageBox.Show("沒有需要反審核的數據", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                else
                {
                    int i = _OrtService.UnApprove(unApproveList);
                    QMessageBox.Show("反審核成功記錄數：" + i.ToString() + "條", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (i > 0)
                    {
                        SysLogService.Log(dbContext, this._User, this, tsmUnApprove.Text
                            , string.Join(",", unApproveList.Select(m => m.BillNo).ToArray())
                            , string.Empty);
                    }
                    foreach (var idx in unApproveIndexs)
                    {
                        _Heads[idx] = _OrtService.GetHeadById(_Heads[idx].Id);
                    }

                    MainDataGridView.Refresh();
                    _CurrentHead = _Heads[currentIndex];
                    BindingControls();
                    picApprove.Visible = false;
                }

                SetControlsEnable();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0020", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void tsmReport_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            //if(cboReport.SelectedItem == null)
            //{
            //    QMessageBox.Show("未选择报表模板，无法导出！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    return;
            //}
            var reports = _ReportSetModels.Where(r => r.Id == _CurrentHead.ReportId);
            if (reports == null || reports.Count() == 0)
            {
                QMessageBox.Show("未选择报表模板，无法导出！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var report = reports.FirstOrDefault();

            if (_CurrentHead == null || _CurrentHead.Id <= 0) return;

            try
            {
                if (_CurrentHead.Dtls.Count == 0)
                {
                    _CurrentHead.Dtls = _OrtService.GetDtls(_CurrentHead.Id);
                }
                if (_CurrentHead.Dtls.Count > 0)
                {
                    foreach (OrtDtlModel dtl in _CurrentHead.Dtls)
                    {
                        if (dtl.Datas.Count == 0)
                        {
                            dtl.Datas = _OrtService.GetDatas(dtl.HeadId, dtl.SNo);
                        }
                    }
                }

                //_OrtService.GenStandard(_CurrentHead, _CurrentHead.Dtls[0]);
                string reportCode = GetReportCode(_CurrentHead.ReportId);
                _OrtService.GenStandard(_CurrentHead, _CurrentHead.Dtls.Count > 0 ? _CurrentHead.Dtls[0] : null, reportCode);

                string path = SysParamService.GetSysParamValue(dbContext, "ReportPath");
                OrtReportFactory.GenOrtReport(_CurrentHead, report, path, true);
                if(!string.IsNullOrEmpty(BaseReport.ErrorMsg))
                {
                    QMessageBox.ShowError(BaseReport.ErrorMsg);
                    BaseReport.ErrorMsg = "";
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0202", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmJiscAll_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {
                List<string> codeList = new List<string>(new string[]
                {
                    "R000","R001","R002","R003","R004","R005","R006","R007","R008","R009","R010","R011","R012","R013","R014"
                });
                var rs = _ReportSetModels.Where(r => codeList.Contains(r.Code)).OrderBy(r => r.Code);
                if (!rs.Any())
                {
                    QMessageBox.Show("報表設置中未找到对应的報表，請先設置報表格式", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                string path = SysParamService.GetSysParamValue(dbContext, "ReportPath");
                OrtReportFactory.GetAllJiscReport(list, rs.ToList(), path, true);
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0503", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmJiscAll_Solid_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {

            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0503", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmAecReports_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {

            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0503", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmAecReports_Solid_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {

            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0503", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmBatchReport_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {
                if (list != null && list.Count > 0)
                    list.ForEach(t => t.IsBatchExport = true);
                string path = SysParamService.GetSysParamValue(dbContext, "ReportPath");
                OrtReportFactory.GetBatchReports(list, _ReportSetModels, path, true);
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0504", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //高溫負荷壽命試驗對比報告
        private void tsmHighTempLife_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {

            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0505", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmStorageLife_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {

            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0506", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        bool BeforeBatchReport(out List<OrtHeadModel> list)
        {
            list = new List<OrtHeadModel>();
            bool flag = true;
            if (MainDataGridView.SelectedRows == null) return false;
            if (MainDataGridView.Rows.Count == 0) return false; ;
            if (MainDataGridView.SelectedRows.Count == 0)
            {
                QMessageBox.Show("請選擇要生成報表的記錄行", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                return false; ;
            }

            try
            {
                for (int i = 0; i < MainDataGridView.SelectedRows.Count; i++)
                {
                    OrtHeadModel m = MainDataGridView.SelectedRows[i].DataBoundItem as OrtHeadModel;
                    if (m == null) continue;
                    if (m.Dtls == null || m.Dtls.Count == 0)
                        m.Dtls = _OrtService.GetDtls(m.Id);
                    List<OrtDataModel> datas = _OrtService.GetDatas(m.Id);
                    if (datas.Count > 0)
                    {
                        foreach (OrtDtlModel item in m.Dtls)
                        {
                            if (item.Datas.Count > 0) continue;
                            var d = datas.Where(t => t.SNo == item.SNo);
                            if (d.Any())
                            {
                                item.Datas.AddRange(d.ToList());
                            }
                        }
                    }

                    string reportCode = GetReportCode(m.ReportId);
                    _OrtService.GenStandard(m, m.Dtls.Count > 0 ? m.Dtls[0] : null, reportCode);

                    list.Add(m);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                return false;
            }

            if (list.Count == 0) return false;

            return flag;
        }
        private void tsmQuery_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Query))
            {
                return;
            }

            try
            {
                if (_FormFilter == null) _FormFilter = new FormOrtFilter(this._User, this._BillType, _ReportSetModels);
                if (_FormFilter.ShowDialog() == DialogResult.OK)
                {
                    BindingData();
                    BindingControls();
                    tabControl.SelectedTab = tabMain;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0029", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsmQueryDtl_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Query))
            {
                return;
            }

            try
            {
                FormOrtDtlQuery f = new FormOrtDtlQuery(this._User, dbContext);
                f.Show();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0029", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void tsmCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("数据还没保存，请确认是否取消", "请确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
    == DialogResult.Cancel)
                    return;

                //if (_FormStatus == FormStatus.Add || _FormStatus == FormStatus.Copy)
                //{
                //    try { _OrtService.Delete(new List<OrtHeadModel>() { _CurrentHead }); }
                //    catch (Exception ex) { Logger.LogError(ex); }
                //}

                LockService.DelLock(dbContext, _LockIds);
                _FormStatus = FormStatus.Browser;
                int columnIndex, rowIndex;
                columnIndex = rowIndex = 0;
                if (MainDataGridView.CurrentRow != null)
                {
                    _CurrentHead = MainDataGridView.CurrentRow.DataBoundItem as OrtHeadModel;
                    rowIndex = MainDataGridView.CurrentRow.Index;
                }
                if (_CurrentHead == null)
                    _CurrentHead = new OrtHeadModel();
                else
                {
                    int index = _Heads.IndexOf(_CurrentHead);
                    _CurrentHead = _OrtService.GetHeadById(_CurrentHead.Id);
                    _CurrentHead.Dtls = _OrtService.GetDtls(_CurrentHead.Id);
                    _CurrentHead.Volts = _OrtService.GetVolts(_CurrentHead.Id);
                    if (index >= 0) _Heads[index] = _CurrentHead;
                }

                if (_Heads != null && _Heads.Count > 0)
                    MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(columnIndex, rowIndex));
                if (_CurrentDtl != null)
                    ViewModelTrans<OrtDataModel>.DataToView(_CurrentDtl.SNo, _CurrentDtl.Datas, _CurrentDtl.ElectricViewModels, _CurrentDtl.SizeViewModels);
                if (_CurrentHead.Dtls.Count > 0)
                {
                    _CurrentHead.Dtls.RemoveAll(d => d.Id <= 0);
                }
                if (_CurrentHead != null) DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                if (_CurrentDtl != null) ElectricDataGridView.DataSource = new BindingList<ElectricViewModel>(_CurrentDtl.ElectricViewModels);
                if (_CurrentHead != null) VDataGridView.DataSource = new BindingList<OrtVoltageModel>(_CurrentHead.Volts);

                BindingControls();
                SetControlsEnable();
                CloseSubForm();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void tsmSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (!this.Validate()) return;
                DtlDataGridView.EndEdit();
                this.Cursor = Cursors.WaitCursor;

                if (BillType == "FQC")
                {
                    if (string.IsNullOrEmpty(_CurrentHead.LotNo))
                        _CurrentHead.LotNo = _CurrentHead.SourceNo;
                    if (string.IsNullOrEmpty(_CurrentHead.Pn))
                        _CurrentHead.Pn = _CurrentHead.SourceNo;
                }

                if (!HeadValidating()) return;
                _CurrentHead.ModiDate = this._User.GetServerTime();
                _CurrentHead.ModiUser = this._User.UserName;

                //是否合格
                if (_CurrentHead.Level == "C") _CurrentHead.IsValid = false;
                else if (_CurrentHead.Level == "B")
                {
                    if(!String.IsNullOrWhiteSpace(_CurrentHead.Remark))
                    {
                        if (_CurrentHead.TestTotalTime > 0
                            && Tools.GetFrontNumberOfString(_CurrentHead.Remark) <= _CurrentHead.TestTotalTime)
                            _CurrentHead.IsValid = false;
                        else
                            _CurrentHead.IsValid = true;
                    }
                }
                else _CurrentHead.IsValid = true;

                if(_CurrentHead.Dtls.Count>0)
                {
                    int maxSno = _CurrentHead.Dtls.Max(t => t.SNo);
                    OrtDtlModel m = _CurrentHead.Dtls.Where(t => t.SNo == maxSno).FirstOrDefault();
                    if(m != null)
                    {
                        _CurrentHead.TestTime = m.TestTime;
                        _CurrentHead.ExpireDate = m.ExpireDate;
                    }
                }

                if (string.IsNullOrWhiteSpace(_CurrentHead.Customer))
                    _CurrentHead.Customer = _CurrentHead.CustomerCode;

                int i = _OrtService.Save(_CurrentHead);


                if (i > 0)
                {
                    
                    QMessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    if (_FormStatus == FormStatus.Add) Settings.SaveObject(_CurrentHead.ToJson(), this.Name);//默认值保存
                    SysLogService.Log(dbContext, this._User, this
                        , _FormStatus == FormStatus.Edit ? tsmEdit.Text : tsmAdd.Text
                        , _CurrentHead.Id.ToString() + "," + _CurrentHead.BillNo, string.Empty);
                    _FormStatus = FormStatus.Browser;
                    _CurrentDtl = null;

                    SetControlsEnable();
                    LockService.DelLock(dbContext, _LockIds);
                    CloseSubForm();
                    if (!_Heads.Contains(_CurrentHead))
                    {
                        isAfterAdd = true;
                        _Heads.Insert(0, _CurrentHead);
                        tssCurrentId.Text = _CurrentHead.Id.ToString();
                        MainDataGridView.DataSource = new BindingList<OrtHeadModel>(_Heads);
                        MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(0, 0));
                        DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                        VDataGridView.DataSource = new BindingList<OrtVoltageModel>(_CurrentHead.Volts);
                        SetTssEnable(0);
                        tssCount.Text = _Heads.Count.ToString();
                    }

                    if(BillType != "FQC")
                        AutoGenReport(_CurrentHead);
                }
                else
                {
                    QMessageBox.Show("保存失敗", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("idx_t_ort_head_billno"))
                {
                    QMessageBox.Show("試驗單號重複：" + txtBillNo.Text, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtBillNo.Focus();
                    return;
                }
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0007", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        bool isAfterAdd = false;

        void IsAutoGenReport()
        {
            BackgroundWorker bk = new BackgroundWorker();
            bk.DoWork += (s, a) =>
             {
                 try
                 {
                     string outpath = SysParamService.GetSysParamValue(dbContext, "OutPath");
                     if (Directory.Exists(outpath))
                     {
                         this.isAutoGenReport = true;
                     }
                 }
                 catch (Exception ex)
                 {
                     Logger.LogError(ex);
                 }
             };

            bk.RunWorkerAsync();
        }
        void AutoGenReport(OrtHeadModel head, string outFileName="")
        {
            if (!isAutoGenReport) return;
            string sysTempFileName = string.Empty;
            BackgroundWorker bk = new BackgroundWorker();
            bk.DoWork += (s, a) =>
            {
                try
                {
                    OrtService tempService = new OrtService(new AllDbContext());
                    string outpath = SysParamService.GetSysParamValue(dbContext, "OutPath");
                    string reportPath = SysParamService.GetSysParamValue(dbContext, "ReportPath");
                    if (Directory.Exists(outpath))
                    {
                        string yearPath = outpath + "\\" + head.TestDate.Year.ToString() + "年";
                        if (!Directory.Exists(yearPath))
                            Directory.CreateDirectory(yearPath);

                        var reportSet = _ReportSetModels.Where(t => t.Id == head.ReportId).FirstOrDefault();
                        if (reportSet == null) return;
                        string typepath = yearPath;

                        if (head.BillType == "TS")
                        {
                            if (reportSet.Code == "R001" || reportSet.Code == "R015" || reportSet.Code == "R016"
                            || reportSet.Code == "R017" || reportSet.Code == "R018" || reportSet.Code == "R020")
                            {
                                typepath = typepath + "\\" + "有载";
                            }
                            else if (reportSet.Code == "R002" || reportSet.Code == "R019")
                            {
                                typepath = typepath + "\\" + "有载";
                            }
                            else
                            {
                                typepath = typepath + "\\" + "其他";
                            }
                        }
                        else
                        {
                            var billtype = _BillTypes.Where(t => t.Code == head.BillType).FirstOrDefault();
                            if(billtype != null)
                            {
                                if(!string.IsNullOrEmpty(billtype.Group))
                                {
                                    typepath = typepath + "\\" + billtype.Group + "\\" + billtype.Name
                                    + "\\" + reportSet.Name;
                                }
                                else
                                {
                                    typepath = typepath + "\\" + billtype.Name + "\\" + reportSet.Name;
                                }
                            }
                            else
                               typepath = typepath + "\\" + "其他" + reportSet.Name;
                        }
                        if (!Directory.Exists(typepath))
                            Directory.CreateDirectory(typepath);

                        string monthPath = typepath + "\\" + head.TestDate.Month.ToString() + "月";

                        if (!Directory.Exists(monthPath))
                            Directory.CreateDirectory(monthPath);

                        if (head.Dtls.Count == 0)
                        {
                            head.Dtls = tempService.GetDtls(head.Id);
                        }
                        if (head.Dtls.Count > 0)
                        {
                            var datas = tempService.GetDatas(head.Id);
                            if (datas.Count > 0)
                            {
                                foreach (OrtDtlModel dtl in head.Dtls)
                                {
                                    if (dtl.Datas.Count == 0)
                                    {
                                        var datsa2 = datas.Where(t=>t.SNo == dtl.SNo).ToList();
                                        if(datsa2.Count > 0)
                                        {
                                            dtl.Datas.Clear();
                                            dtl.Datas.AddRange(datsa2);
                                        }
                                        //dtl.Datas = tempService.GetDatas(dtl.HeadId, dtl.SNo);
                                    }
                                }
                            }
                        }

                        
                        IWorkbook workbook = OrtReportFactory.GenOrtReport(head, reportSet, reportPath, false);
                        string errorMsg;
                        string fileName = Settings.GetReportFileName(outpath, reportSet.Path, out errorMsg);
                        if (!string.IsNullOrWhiteSpace(outFileName))
                            sysTempFileName = outFileName;
                        else
                        sysTempFileName = monthPath + "\\"
                            + OrtReportFactory.GetExcelTempFileName(head, reportSet)//+ Guid.NewGuid().ToString()
                            + "-"
                            + fileName.Substring(fileName.LastIndexOf('\\')+1);

                        using (FileStream fs = new FileStream(sysTempFileName, FileMode.Create, FileAccess.Write))
                        {
                            MemoryStream stream = new MemoryStream();
                            workbook.Write(stream);
                            var buf = stream.ToArray();
                            fs.Write(buf, 0, buf.Length);
                            fs.Flush();
                        }

                        if(!string.IsNullOrEmpty(BaseReport.ErrorMsg))
                        {
                            throw new Exception(BaseReport.ErrorMsg);
                        }
                    }
                }
                catch (Exception ex)
                {
                    SysLogService.Log(dbContext, _User, 
                        this, LanguageHelper.GetLanguageText("保存自动导出报表异常"), _CurrentHead.BillNo, ex.Message + " : " + sysTempFileName);
                    if(ex.Message.Contains("正由另一进程使用"))
                    {
                        string filename = sysTempFileName.Replace(".xls", Path.GetRandomFileName() +  ".xls");
                        AutoGenReport(head, filename);
                    }else throw ex;
                }
            };

            bk.RunWorkerCompleted += (s, a) =>
            {
                if (a.Error != null)
                {
                    QMessageBox.ShowError(a.Error.Message);
                    BaseReport.ErrorMsg = "";
                }
            };

            bk.RunWorkerAsync();

        }

        //導出列表
        private void tsmSumExport_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = RandomSugar.GetFileRndName() + ".xlsx";
                fileName = NPOIHelper.DataGridViewToExcel(fileName, MainDataGridView, "Arial", 11, true, "試驗匯總明細表");
                if (File.Exists(fileName))
                {
                    Process.Start(fileName);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0032", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        //匯總表
        private void tsmSumExport_Elite_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight(this, this._User, RightType.Export)) return;

            List<OrtHeadModel> list;
            if (!BeforeBatchReport(out list)) return;

            try
            {
                if (list != null && list.Count > 0)
                {
                    list.ForEach(t => t.IsBatchExport = true);
                    list.Sort((x, y) => {
                        if (x.ExpireDate.HasValue && y.ExpireDate.HasValue)
                            return x.ExpireDate.Value.CompareTo(y.ExpireDate.Value);
                        else if (x.ExpireDate.HasValue && !y.ExpireDate.HasValue)
                            return 1;
                        else if (!x.ExpireDate.HasValue && y.ExpireDate.HasValue)
                            return -1;
                        else return 0;
                    });
                }
                string path = SysParamService.GetSysParamValue(dbContext, "ReportPath");
                var report = _ReportSetModels.Where(t => t.Id == list[0].ReportId).FirstOrDefault();
                OrtReportFactory.GetSumReports(list, report, path, true);
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, "異常S0504", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion 工具栏

        bool HeadValidating()
        {
            bool flag = true;
            if (string.IsNullOrWhiteSpace(_CurrentHead.BillNo))
            {
                QMessageBox.Show("試驗單號不能為空！","錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBillNo.Focus();
                flag = false;
            }
            else if (string.IsNullOrWhiteSpace(_CurrentHead.LotNo))
            {
                QMessageBox.Show("試驗批號不能為空！", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtLotNo.Focus();
                flag = false;
            }
            else if (string.IsNullOrWhiteSpace(_CurrentHead.Pn))
            {
                QMessageBox.Show("料号不能為空！", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPn.Focus();
                flag = false; 
            }

            //文件名是否合法
            else if (!Tools.FileNameIsValid(_CurrentHead.BillNo))
            {
                QMessageBox.Show("試驗單號包含非法字符！", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBillNo.Focus();
                flag = false;
            }
            else if (!Tools.FileNameIsValid(_CurrentHead.LotNo))
            {
                QMessageBox.Show("試驗批號包含非法字符！", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtLotNo.Focus();
                flag = false;
            }
            else if (!Tools.FileNameIsValid(_CurrentHead.Pn))
            {
                QMessageBox.Show("料号包含非法字符！","錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPn.Focus();
                flag = false;
            }

            if (!string.IsNullOrWhiteSpace(txtSeries.Text))
            {
                if (!Tools.IsNumAndEnCh(txtSeries.Text))
                {
                    QMessageBox.Show("系列包含非法字符", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtSeries.Focus();
                    flag = false;
                }
            }

            if (!string.IsNullOrWhiteSpace(txtRipperCurrent.Text) && cboTestFreq.SelectedIndex < 0)
            {
                MessageBox.Show("請選擇頻率", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                cboTestFreq.Focus();
                flag = false;
            }

            return flag;
        }

        void BindingData()
        {
            try
            {
                DtlDataGridView.DataSource = _EmptyDtlModels;
                ElectricDataGridView.DataSource = _EmptyElectricViews;
                //SizeDataGridView.DataSource = _EmptySizeViews;

                if (_FormFilter == null)
                    _Heads = _OrtService.GetHeads(_MaxRowCount, this._BillType);
                else
                    _Heads = _OrtService.Query(_FormFilter.Filter);

                MainDataGridView.DataSource = new BindingList<OrtHeadModel>(_Heads);
                //MainDataGridView.DataSource = new SortableBindingList<OrtHeadModel>();
                MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(0, 0));
                if (_Heads != null && _Heads.Count > 0)
                    tssCount.Text = _Heads.Count.ToString();
                else
                    tssCount.Text = "0";

                if (_Heads != null && _Heads.Count > 0)
                    SetTssEnable(0);
                else
                    SetTssEnable(-1);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0008"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void BindingControls()
        {
            try
            {

                #region
                /*
                cboSourceCode.DataBindings.Clear();
                txtSourceNo.DataBindings.Clear();
                numSourceSNo.DataBindings.Clear();
                txtLotNo.DataBindings.Clear();
                txtCustomer.DataBindings.Clear();
                txtCustomerCode.DataBindings.Clear();
                dteTestDate.DataBindings.Clear();
                txtSeries.DataBindings.Clear();
                txtCap.DataBindings.Clear();
                txtVoltage.DataBindings.Clear();
                txtSize.DataBindings.Clear();
                txtFoilP.DataBindings.Clear();
                txtFoilN.DataBindings.Clear();
                txtLeadWire.DataBindings.Clear();
                txtEps.DataBindings.Clear();
                txtPaste.DataBindings.Clear();
                txtRubber.DataBindings.Clear();
                txtAlCase.DataBindings.Clear();
                //txtReportId.DataBindings.Clear();
                cboReport.DataBindings.Clear();
                txtElectricQty.DataBindings.Clear();
                txtSizeQty.DataBindings.Clear();
                txtCapRate.DataBindings.Clear();
                txtDfMax.DataBindings.Clear();
                txtDfMaxAfter.DataBindings.Clear();
                txtLcMax.DataBindings.Clear();
                txtZMax.DataBindings.Clear();
                txtZRate.DataBindings.Clear();
                txtZRate2.DataBindings.Clear();
                txtEsrMax.DataBindings.Clear();
                txtEsrMaxAfter.DataBindings.Clear();
                txtTestTemp.DataBindings.Clear();
                txtTestVoltage.DataBindings.Clear();
                txtTestTotalTime.DataBindings.Clear();
                txtBoxNo.DataBindings.Clear();
                txtBillNo.DataBindings.Clear();
                cboTestTarget.DataBindings.Clear();
                txtRipperCurrent.DataBindings.Clear();
                dteFinishDate.DataBindings.Clear();
                txtLcrMeter.DataBindings.Clear();
                txtLcMeter.DataBindings.Clear();
                txtOtherMachine.DataBindings.Clear();
                cboLevel.DataBindings.Clear();
                cboTestFreq.DataBindings.Clear();
                txtRemark.DataBindings.Clear();
                txtPn.DataBindings.Clear();
                txtCustomerPn.DataBindings.Clear();
                txtBillType.DataBindings.Clear();
                txtId.DataBindings.Clear();
                txtCapRate2.DataBindings.Clear();
                txtWeightMax.DataBindings.Clear();
                txtcp.DataBindings.Clear();
                txtTestHumidity.DataBindings.Clear();
                txtCapMin.DataBindings.Clear();
                txtCapMax.DataBindings.Clear();
                txtDateCode.DataBindings.Clear();
                txtFoilpSupplier.DataBindings.Clear();
                dteSampleDate.DataBindings.Clear();
                txtBadDesc.DataBindings.Clear();
                txtBadReason.DataBindings.Clear();
                txtDeliveryQty.DataBindings.Clear();
                txtLcTime.DataBindings.Clear();

                txtDMax.DataBindings.Clear();
                txtLMax.DataBindings.Clear();
                txtFMax.DataBindings.Clear();

                txtLcMaxAfter.DataBindings.Clear();

                chkIsValid.DataBindings.Clear();

                cboBillType.DataBindings.Clear();


                if (_CurrentHead == null) return;
                cboSourceCode.DataBindings.Add("SelectedValue", _CurrentHead, "SourceCode");
                txtSourceNo.DataBindings.Add("Text", _CurrentHead, "SourceNo");
                numSourceSNo.DataBindings.Add("Value", _CurrentHead, "SourceSNo");
                txtLotNo.DataBindings.Add("Text", _CurrentHead, "LotNo");
                txtCustomer.DataBindings.Add("Text", _CurrentHead, "Customer");
                txtCustomerCode.DataBindings.Add("Text", _CurrentHead, "CustomerCode");
                dteTestDate.DataBindings.Add("Value", _CurrentHead, "TestDate");
                txtSeries.DataBindings.Add("Text", _CurrentHead, "Series");
                txtCap.DataBindings.Add("Text", _CurrentHead, "Cap");
                txtVoltage.DataBindings.Add("Text", _CurrentHead, "Voltage");
                txtSize.DataBindings.Add("Text", _CurrentHead, "Size");
                txtFoilP.DataBindings.Add("Text", _CurrentHead, "FoilP");
                txtFoilN.DataBindings.Add("Text", _CurrentHead, "FoilN");
                txtLeadWire.DataBindings.Add("Text", _CurrentHead, "LeadWire");
                txtEps.DataBindings.Add("Text", _CurrentHead, "Eps");
                txtPaste.DataBindings.Add("Text", _CurrentHead, "Paste");
                txtRubber.DataBindings.Add("Text", _CurrentHead, "Rubber");
                txtAlCase.DataBindings.Add("Text", _CurrentHead, "AlCase");
                //txtReportId.DataBindings.Add("Text", _CurrentOrtHeadModel, "ReportId");
                cboReport.DataBindings.Add("SelectedValue", _CurrentHead, "ReportId");
                txtElectricQty.DataBindings.Add("Text", _CurrentHead, "ElectricQty");
                txtSizeQty.DataBindings.Add("Text", _CurrentHead, "SizeQty");
                txtCapRate.DataBindings.Add("Text", _CurrentHead, "CapRate");
                txtDfMax.DataBindings.Add("Text", _CurrentHead, "DfMax");
                txtDfMaxAfter.DataBindings.Add("Text", _CurrentHead, "DfMaxAfter");
                txtLcMax.DataBindings.Add("Text", _CurrentHead, "LcMax");
                txtZMax.DataBindings.Add("Text", _CurrentHead, "ZMax");
                txtZRate.DataBindings.Add("Text", _CurrentHead, "ZRate");
                txtZRate2.DataBindings.Add("Text", _CurrentHead, "ZRate2");
                txtEsrMax.DataBindings.Add("Text", _CurrentHead, "EsrMax");
                txtEsrMaxAfter.DataBindings.Add("Text", _CurrentHead, "EsrMaxAfter");
                txtTestTemp.DataBindings.Add("Text", _CurrentHead, "TestTemp");
                txtTestVoltage.DataBindings.Add("Text", _CurrentHead, "TestVoltage");
                txtTestTotalTime.DataBindings.Add("Text", _CurrentHead, "TestTotalTime");
                txtBoxNo.DataBindings.Add("Text", _CurrentHead, "BoxNo");
                txtBillNo.DataBindings.Add("Text", _CurrentHead, "BillNo");
                cboTestTarget.DataBindings.Add("SelectedValue", _CurrentHead, "TestTarget");
                txtRipperCurrent.DataBindings.Add("Text", _CurrentHead, "RippleCurrent");
                dteFinishDate.DataBindings.Add("Text", _CurrentHead, "FinishDate");
                txtLcrMeter.DataBindings.Add("Text", _CurrentHead, "LcrMeter");
                txtLcMeter.DataBindings.Add("Text", _CurrentHead, "LcMeter");
                txtOtherMachine.DataBindings.Add("Text", _CurrentHead, "OtherMachine");
                cboLevel.DataBindings.Add("SelectedValue", _CurrentHead, "Level");
                cboTestFreq.DataBindings.Add("SelectedValue", _CurrentHead, "TestFreq");
                txtRemark.DataBindings.Add("Text", _CurrentHead, "Remark");
                txtPn.DataBindings.Add("Text", _CurrentHead, "Pn");
                txtCustomerPn.DataBindings.Add("Text", _CurrentHead, "CustomerPn");
                txtBillType.DataBindings.Add("Text", _CurrentHead, "BillType");
                txtId.DataBindings.Add("Text", _CurrentHead, "Id");
                txtCapRate2.DataBindings.Add("Text", _CurrentHead, "CapRate2");
                txtWeightMax.DataBindings.Add("Text", _CurrentHead, "WeightMax");
                txtcp.DataBindings.Add("Text", _CurrentHead, "cp");
                txtTestHumidity.DataBindings.Add("Text", _CurrentHead, "TestHumidity");
                txtCapMin.DataBindings.Add("Text", _CurrentHead, "CapMin");
                txtCapMax.DataBindings.Add("Text", _CurrentHead, "CapMax");
                txtDateCode.DataBindings.Add("Text", _CurrentHead, "DateCode");
                txtFoilpSupplier.DataBindings.Add("Text", _CurrentHead, "FoilpSupplier");
                dteSampleDate.DataBindings.Add("Value", _CurrentHead, "SampleDate");

                txtBadDesc.DataBindings.Add("Text", _CurrentHead, "BadDesc");
                txtBadReason.DataBindings.Add("Text", _CurrentHead, "BadReason");

                txtDeliveryQty.DataBindings.Add("Text", _CurrentHead, "DeliveryQty");
                txtLcTime.DataBindings.Add("Text", _CurrentHead, "LcTime");

                txtDMax.DataBindings.Add("Text", _CurrentHead, "DMax");
                txtLMax.DataBindings.Add("Text", _CurrentHead, "LMax");
                txtFMax.DataBindings.Add("Text", _CurrentHead, "FMax");

                txtLcMaxAfter.DataBindings.Add("Text", _CurrentHead, "LcMaxAfter");

                chkIsValid.DataBindings.Add("Checked", _CurrentHead, "IsValid");

                cboBillType.DataBindings.Add("SelectedValue", _CurrentHead, "BillType");
                */

                QControlBingding.BindingControls(this, _CurrentHead);

                tssCurrentId.Text = _CurrentHead.Id.ToString();
                #endregion
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0016"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void SetControlsEnable()
        {
            try
            {
                bool isEdit = (_FormStatus != FormStatus.Browser);

                #region 工具欄
                //tsmAdd.Visible = !isEdit;
                tsmDelete.Visible = !isEdit;
                tsmApprove.Visible = !isEdit;
                tsmUnApprove.Visible = !isEdit;
                tsmQueryDtl.Visible = !isEdit;


                tsmCancel.Visible = isEdit;
                //tsmTest.Visible = isEdit;
                tsmSave.Visible = isEdit;


                tsmAdd.Enabled = !isEdit;
                tsmCancel.Enabled = isEdit;
                tsmApprove.Enabled = !isEdit;
                tsmCopy.Enabled = !isEdit;
                tsmCopy2.Enabled = !isEdit;
                tsmDelete.Enabled = !isEdit;
                tsmEdit.Enabled = !isEdit;
                tsmQuery.Enabled = !isEdit;
                tsmQueryDtl.Enabled = !isEdit;
                tsmReport.Enabled = !isEdit;
                tsmSave.Enabled = isEdit;
                //tsmTest.Enabled = isEdit;
                tsmLcr_Double.Enabled = !isEdit;
                tsmLcrTest.Enabled = isEdit;
                tsmLcTest.Enabled = isEdit;
                tsmSizeTest.Enabled = isEdit;
                tsmUnApprove.Enabled = !isEdit;
                tsmExit.Enabled = !isEdit;
                tsmSumExport.Enabled = !isEdit;
                #endregion 工具欄

                FormCommon.SetControlEnable(this, isEdit);

                if (_FormStatus == FormStatus.Edit)
                {
                    //numElectricQty.Enabled = false;
                    //numSizeQty.Enabled = false;
                    cboSourceCode.Enabled = false;
                    txtSourceNo.ReadOnly = true;
                    numSourceSNo.ReadOnly = true;
                    txtBillNo.ReadOnly = true;
                }

                if (_FormStatus == FormStatus.Browser)
                {
                    //MainDataGridView.Enabled = true;
                    DtlDataGridView.ReadOnly = true;
                    //SizeDataGridView.ReadOnly = true;
                    VDataGridView.ReadOnly = true;
                    ElectricDataGridView.ReadOnly = true;
                    if (string.IsNullOrWhiteSpace(_CurrentHead.ApproveUser))
                    {
                        tsmApprove.Enabled = true;
                        tsmUnApprove.Enabled = false;
                        tsmDelete.Enabled = true;
                        tsmEdit.Enabled = true;
                    }
                    else
                    {
                        tsmApprove.Enabled = false;
                        tsmUnApprove.Enabled = true;
                        tsmDelete.Enabled = false;
                        tsmEdit.Enabled = false;
                    }

                    if (_CurrentHead == null || _CurrentHead.Id <= 0)
                    {
                        tsmApprove.Enabled = false;
                        tsmUnApprove.Enabled = false;
                        tsmCopy.Enabled = false;
                        tsmCopy2.Enabled = false;
                        tsmDelete.Enabled = false;
                        tsmEdit.Enabled = false;
                        tsmReport.Enabled = false;
                        tsmSumExport.Enabled = false;
                    }
                }
                else
                {
                    MainDataGridView.Enabled = false;
                    DtlDataGridView.ReadOnly = false;
                    VDataGridView.ReadOnly = false;
                    //SizeDataGridView.ReadOnly = false;
                    ElectricDataGridView.ReadOnly = false;
                }

                dteFinishDate.Enabled = false;

                bool isAutoTest = Settings.IsAllAuto();
                if (isAutoTest) tsmLcTest.Visible = false;

                if (_FormStatus == FormStatus.Browser && tabControl.SelectedTab == tabMain)
                {
                    MainDataGridView.Enabled = true;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0017"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MainDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                OrtHeadModel head = null;
                if (MainDataGridView.Rows.Count > 0)
                    head = MainDataGridView.Rows[e.RowIndex].DataBoundItem as OrtHeadModel;
                if (_CurrentHead == head) return;
                _CurrentHead = head;
                if (_CurrentHead == null) _CurrentHead = new OrtHeadModel();
                picApprove.Visible = !string.IsNullOrWhiteSpace(_CurrentHead.ApproveUser);
                tssCurrentId.Text = _CurrentHead.Id.ToString();
                int currentRowIndex = _Heads.IndexOf(_CurrentHead);
                SetTssEnable(currentRowIndex);

                if (_CurrentHead.Dtls == null || _CurrentHead.Dtls.Count == 0)
                {
                    List<OrtDtlModel> dtls = _OrtService.GetDtls(_CurrentHead.Id);
                    if (dtls != null && dtls.Count > 0)
                        _CurrentHead.Dtls = dtls;
                }
                DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                DtlDataGridView_RowEnter(DtlDataGridView, new DataGridViewCellEventArgs(0, 0));

                if (_CurrentHead != null && _ReportSetModels.Count > 0)
                {
                    var report = _ReportSetModels.Where(t => t.Id == _CurrentHead.ReportId).FirstOrDefault();
                    if (report != null)
                    {
                        Col_ESR2.Visible = report.HasEsr2;
                        Col_Z2.Visible = report.HasZ2;
                    }
                }

                //过压
                if (_CurrentHead != null && _ReportSetModels.Count > 0)
                {
                    var report = _ReportSetModels.Where(t => t.Id == _CurrentHead.ReportId).FirstOrDefault();
                    if (report != null)
                    {
                        Col_ESR2.Visible = report.HasEsr2;
                        Col_Z2.Visible = report.HasZ2;

                        if (report.Code == "R021")
                        {
                            if (_CurrentHead.Volts.Count <= 0)
                            {
                                try
                                {
                                    _CurrentHead.Volts.AddRange(_OrtService.GetVolts(_CurrentHead.Id));
                                }
                                catch (Exception ex)
                                {
                                    Logger.LogError(ex);
                                }
                            }
                        }
                    }
                }
                VDataGridView.DataSource = new BindingList<OrtVoltageModel>(_CurrentHead.Volts);
                SetAfterStandard();

                BindingControls();
                SetControlsEnable();
                MainDataGridView.Focus();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0021"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void DtlDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //Stopwatch sp = new Stopwatch();
                //StringBuilder sb = new StringBuilder();
                //sp.Start();
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                if (DtlDataGridView.Rows.Count == 0 || DtlDataGridView.Rows[e.RowIndex] == null)
                {
                    _CurrentDtl = null;
                    ElectricDataGridView.DataSource = new BindingList<ElectricViewModel>(_EmptyElectricViews);
                    //SizeDataGridView.DataSource = new BindingList<SizeViewModel>(_EmptySizeViews);
                    return;
                }

                OrtDtlModel dtl = DtlDataGridView.Rows[e.RowIndex].DataBoundItem as OrtDtlModel;
                if (_CurrentDtl == dtl) return;
                _CurrentDtl = dtl;
                if (dtl.Datas == null || dtl.Datas.Count == 0)
                {
                    if (_FormStatus == FormStatus.Browser ||
                        (_FormStatus != FormStatus.Browser && ElectricDataGridView.Rows.Count == 0
                        //&& SizeDataGridView.Rows.Count == 0
                        )
                        )
                    {
                        var ds = _OrtService.GetDatas(_CurrentHead, dtl);
                        if (ds != null) dtl.Datas = _OrtService.GetDatas(_CurrentHead, dtl);
                    }
                    //dtl.Datas = _OrtService.GetDatas(_CurrentHead, dtl);
                }
                //if(dtl.Datas.Count>0 &&  ElectricDataGridView.Rows.Count == 0 && SizeDataGridView.Rows.Count ==0)
                if (dtl.Datas.Count > 0 && _FormStatus == FormStatus.Browser)
                {
                    ViewModelTrans<OrtDataModel>.DataToView(dtl.SNo, dtl.Datas, dtl.ElectricViewModels, dtl.SizeViewModels);
                }

                string reportCode = GetReportCode(_CurrentHead.ReportId);
                _OrtService.GenStandard(_CurrentHead, _CurrentDtl, reportCode);
                ElectricDataGridView.DataSource = new BindingList<ElectricViewModel>(dtl.ElectricViewModels);
                //SizeDataGridView.DataSource = new BindingList<SizeViewModel>(dtl.SizeViewModels);
                //sb.AppendLine(sp.Elapsed.TotalSeconds.ToString());
                //Logger.LogMessage(sb.ToString());
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0021"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 绑定检测数据网格数据源
        /// </summary>
        /// <param name="datas"></param>
        void BindDataGridSource(List<ElectricViewModel> datas)
        {
            ElectricDataGridView.DataSource = new BindingList<ElectricViewModel>(datas);

        }

        private void tabControl_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (_FormStatus == FormStatus.Browser)
            {
                if (MainDataGridView.Enabled == false)
                {
                    MainDataGridView.Enabled = true;
                    //MainDataGridView.Refresh();
                }
            }
        }

        private void MainDataGridView_DoubleClick(object sender, EventArgs e)
        {
            tabControl.SelectedTab = tabDtl;
        }

        private void FormOrt_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_FormStatus != FormStatus.Browser)
            {
                if (QMessageBox.Show(LanguageHelper.GetLanguageText("正在編輯單據，需要直接退出嗎？")
                    , LanguageHelper.GetLanguageText("請確認"), MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                    == DialogResult.Cancel
                    )
                {
                    e.Cancel = true;
                    return;
                }
            }

            try
            {
                LockService.DelLock(dbContext, _LockIds);
                if (SubFormList.Count > 0)
                {
                    SubFormList.ForEach(f => f.Close());
                }

                DataGridViewColumnStyle.SaveColumnStyle(this._User.UserCode, this.Name, MainDataGridView);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void cboReport_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void dteFinishDate_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (dteFinishDate.Value.Year > 2098)
                    dteFinishDate.CustomFormat = " ";
                else
                    dteFinishDate.CustomFormat = _DefaultDateFomat;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        void CloseSubForm()
        {
            if (SubFormList == null || SubFormList.Count == 0) return;
            try
            {
                SubFormList.ForEach(f => f.Close());
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        #region 狀態欄上下翻按鈕
        private void tssFirst_Click(object sender, EventArgs e)
        {
            if (_FormStatus != FormStatus.Browser) return;
            try
            {
                if (MainDataGridView.Rows.Count > 0)
                {
                    MainDataGridView.ClearSelection();
                    MainDataGridView.Rows[0].Selected = true;
                    MainDataGridView.Rows[0].Cells[0].Selected = true;
                    MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(0, 0));
                    SetTssEnable(0);
                    MainDataGridView.FirstDisplayedScrollingRowIndex =0;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void tssPre_Click(object sender, EventArgs e)
        {
            if (_FormStatus != FormStatus.Browser) return;
            try
            {
                int rowIndex = 0;
                if (MainDataGridView.SelectedRows.Count > 0)
                {
                    rowIndex = MainDataGridView.SelectedRows[0].Index;
                }

                rowIndex--;
                if (rowIndex <= MainDataGridView.Rows.Count - 1 && rowIndex >= 0)
                {
                    MainDataGridView.ClearSelection();
                    MainDataGridView.Rows[rowIndex].Selected = true;
                    MainDataGridView.Rows[rowIndex].Cells[0].Selected = true;
                    MainDataGridView_RowEnter(MainDataGridView
                        , new DataGridViewCellEventArgs(0, rowIndex));
                    SetTssEnable(rowIndex);
                    try
                    {
                        if(MainDataGridView.FirstDisplayedScrollingRowIndex > 1)
                        MainDataGridView.FirstDisplayedScrollingRowIndex =
                            MainDataGridView.FirstDisplayedScrollingRowIndex - 1;
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void tssNext_Click(object sender, EventArgs e)
        {
            if (_FormStatus != FormStatus.Browser) return;
            try
            {
                int rowIndex = 0;
                if (MainDataGridView.SelectedRows.Count > 0)
                {
                    rowIndex = MainDataGridView.SelectedRows[0].Index;
                }
                rowIndex++;
                if (rowIndex <= MainDataGridView.Rows.Count - 1 && rowIndex >= 0)
                {
                    MainDataGridView.ClearSelection();
                    MainDataGridView.Rows[rowIndex].Selected = true;
                    MainDataGridView.Rows[rowIndex].Cells[0].Selected = true;
                    MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(0, rowIndex));
                    SetTssEnable(rowIndex);
                    try
                    {
                        if (MainDataGridView.FirstDisplayedScrollingRowIndex < MainDataGridView.Rows.Count - 2)
                            MainDataGridView.FirstDisplayedScrollingRowIndex =
                            MainDataGridView.FirstDisplayedScrollingRowIndex + 1;
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void tssLast_Click(object sender, EventArgs e)
        {
            if (_FormStatus != FormStatus.Browser) return;
            try
            {
                if (MainDataGridView.Rows.Count > 0)
                {
                    MainDataGridView.ClearSelection();
                    MainDataGridView.Rows[MainDataGridView.Rows.Count - 1].Selected = true;
                    MainDataGridView.Rows[MainDataGridView.Rows.Count - 1].Cells[0].Selected = true;
                    MainDataGridView_RowEnter(MainDataGridView, new DataGridViewCellEventArgs(0, MainDataGridView.Rows.Count - 1));
                    SetTssEnable(MainDataGridView.Rows.Count - 1);
                    MainDataGridView.FirstDisplayedScrollingRowIndex = MainDataGridView.Rows.Count-1;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 狀態欄上下翻按鈕可用設置
        /// </summary>
        /// <param name="rowIndex"></param>
        void SetTssEnable(int rowIndex)
        {
            try
            {
                if (rowIndex >= 0)
                {
                    tssPre.Enabled = true;
                    tssNext.Enabled = true;
                    tssFirst.Enabled = true;
                    tssLast.Enabled = true;
                }
                else
                {
                    tssPre.Enabled = false;
                    tssNext.Enabled = false;
                    tssFirst.Enabled = false;
                    tssLast.Enabled = false;
                }

                if (rowIndex >= MainDataGridView.Rows.Count - 1)
                {
                    tssLast.Enabled = false;
                    tssNext.Enabled = false;
                }
                else if (rowIndex <= 0)
                {
                    tssFirst.Enabled = false;
                    tssPre.Enabled = false;
                }

                tssCurrentRowIndex.Text = (rowIndex + 1).ToString();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }
        #endregion 狀態欄上下翻按鈕

        private void MainDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (MainDataGridView.Columns[e.ColumnIndex] == ColFinishDate)
            {
                if (e.Value != null && e.Value.ToString().Contains("2099"))
                {
                    e.Value = string.Empty;
                }
            }
        }

        private void TxtSize_LostFocus(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;

            if (!string.IsNullOrWhiteSpace(txtSeries.Text)
                && !string.IsNullOrWhiteSpace(txtCap.Text)
                && !string.IsNullOrWhiteSpace(txtVoltage.Text)
                )
            {
                if (QMessageBox.Show(LanguageHelper.GetLanguageText("是否填充數據？")
                    , LanguageHelper.GetLanguageText("請確認"), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                    == DialogResult.No)
                    return;

                double cap = 0;
                double.TryParse(txtCap.Text, out cap);
                double voltage = 0;
                double.TryParse(txtVoltage.Text, out voltage);
                var headTemps = dbContext.QcDb.Queryable<OrtHeadModel>()
                    .Where(h => h.Series == txtSeries.Text && h.Cap == cap
                    && h.Voltage == voltage && h.Size == txtSize.Text)
                    .OrderBy(h => h.CreateDate, OrderByType.Desc);
                if (headTemps != null && headTemps.Count() > 0)
                {
                    var headTemp = headTemps.First();
                    _CurrentHead.FoilP = headTemp.FoilP;
                    _CurrentHead.FoilN = headTemp.FoilN;
                    _CurrentHead.LeadWire = headTemp.LeadWire;
                    _CurrentHead.Eps = headTemp.Eps;
                    _CurrentHead.Paste = headTemp.Paste;
                    _CurrentHead.Rubber = headTemp.Rubber;
                    _CurrentHead.AlCase = headTemp.AlCase;

                    _CurrentHead.CapRate = headTemp.CapRate;
                    _CurrentHead.DfMax = headTemp.DfMax;
                    _CurrentHead.DfMaxAfter = headTemp.DfMaxAfter;
                    _CurrentHead.LcMax = headTemp.LcMax;
                    _CurrentHead.LcMaxAfter = headTemp.LcMaxAfter;
                    if (_CurrentHead.LcMaxAfter == 0)
                        _CurrentHead.LcMaxAfter = _CurrentHead.LcMax;
                    _CurrentHead.ZMax = headTemp.ZMax;
                    _CurrentHead.EsrMax = headTemp.EsrMax;
                    _CurrentHead.EsrMaxAfter = headTemp.EsrMaxAfter;

                    headTemp = null;
                }
            }
        }

        private void txtSize_Validating(object sender, CancelEventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;

            string msg = LanguageHelper.GetLanguageText("尺寸格式錯誤，正確格式為： D*L, 例如：16*20");
            double value;
            try
            {
                if (!string.IsNullOrWhiteSpace(txtSize.Text))
                {
                    if (txtSize.Text.Split('*').Length != 2
                        || !double.TryParse(txtSize.Text.Split('*')[0], out value)
                        || !double.TryParse(txtSize.Text.Split('*')[1], out value)
                        )
                    {
                        QMessageBox.Show(msg, LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        e.Cancel = true;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        bool isChangingTestDate = false;

        private void DteTestDate_LostFocus(object sender, EventArgs e)
        {
            try
            {
                if (isChangingTestDate) return;
                isChangingTestDate = true;
                if (_FormStatus == FormStatus.Browser || _FormStatus == FormStatus.Edit)
                    return;
                if (string.IsNullOrWhiteSpace(txtBillNo.Text))
                    return;
                if (dteTestDate.Value.Date.ToString("yyMMdd") == _CurrentHead.TestDate.Date.ToString("yyMMdd"))
                    return;

                _CurrentHead.TestDate = dteTestDate.Value;
                txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, false);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0036"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                isChangingTestDate = false;
            }
        }

        private void btnAddDtl_Click(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;
            if (_CurrentHead == null) return;
            if (QMessageBox.Show(LanguageHelper.GetLanguageText("即將新增檢測次數，請確認")
                , LanguageHelper.GetLanguageText("請確認"), MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
                == DialogResult.Cancel)
                return;
            DtlDataGridView.EndEdit();

            try
            {
                int sno = 1;
                if (_CurrentHead.Dtls.Count > 0)
                {
                    sno = _CurrentHead.Dtls.Max(d => d.SNo);
                    if (_CurrentHead.Dtls.Where(d => d.SNo == sno).First().TestTime <= 0 && sno > 1
                        )
                    {
                        QMessageBox.Show(LanguageHelper.GetLanguageText("請輸入測試時間")
                            , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    sno++;
                }

                OrtDtlModel preDtl = null;
                OrtDtlModel dtl = new OrtDtlModel(_CurrentHead.ElectricQty, _CurrentHead.SizeQty
                    , sno, _CurrentHead.Id);
                dtl.CreateUser = _User.UserName;
                if (_CurrentHead.Dtls.Count > 0)
                {
                    preDtl = _CurrentHead.Dtls[_CurrentHead.Dtls.Count - 1];
                    dtl.TestTime = preDtl.TestTime + 500;
                }

                _CurrentHead.Dtls.Add(dtl);
                DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                this.DtlDataGridView.FirstDisplayedScrollingRowIndex = this.DtlDataGridView.Rows.Count - 1;
                this.DtlDataGridView.CurrentCell = this.DtlDataGridView.Rows[DtlDataGridView.Rows.Count - 1].Cells[Col_D_SNo.Index];//设定当前行

                dtl.ExpireDate = FormCommon.GetExpireDate(dtl.TestDate, dtl.TestTime - (preDtl == null ? 0 : preDtl.TestTime));
                dtl.Temp = "25℃/55%RH";
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0073")
                    , MessageBoxButtons.OK, MessageBoxIcon.Error);
                Logger.LogError(ex);
            }
        }

        private void DtlDataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                DataGridViewColumn culomn = DtlDataGridView.Columns[e.ColumnIndex];
                if (culomn == null) return;
                if (culomn == Col_D_SNo || culomn == Col_D_CreateUser)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void DtlDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        /// <summary>
        /// 刷新檢測後的網格數據: 0 電氣網格   1尺寸網格
        /// </summary>
        public void RefreshTestGrid(List<ElectricViewModel> list, bool isDoubleTest)
        {
            try
            {
                var db = new AllDbContext();
                var _OrtService1 = new OrtService(db);
                if (isDoubleTest)
                {
                    //同时测两个批次的保存
                    try
                    {
                        List<OrtHeadModel> headGenReportList = new List<OrtHeadModel>();
                        if (_OrtService1.SaveDoubleTest(list))
                        {
                            List<string> billNos = new List<string>();
                            var headIds = list.Select(t => t.HeadId).Distinct().ToList();
                            for (int i = 0; i < headIds.Count; i++)
                            {
                                var head = _Heads.Where(t => t.Id == headIds[i]).FirstOrDefault();
                                if (head == null)
                                {
                                    head = _OrtService1.GetHeadById(headIds[i]);
                                    if (head != null) headGenReportList.Add(head);
                                    continue;
                                }

                                billNos.Add(head.BillNo);

                                var snos = list.Where(t => t.HeadId == headIds[i]).Select(t => t.SNo).Distinct().ToList();
                                if (snos == null || snos.Count == 0) continue;
                                for (int j = 0; j < snos.Count; j++)
                                {
                                    var dtl = head.Dtls.Where(t => t.SNo == snos[j]).FirstOrDefault();
                                    if (dtl == null) continue;
                                    var dataViews = list.Where(t => t.HeadId == headIds[i] && t.SNo == snos[j]).ToList();
                                    if (dataViews == null || dataViews.Count == 0) continue;
                                    dtl.ElectricViewModels.Clear();
                                    dtl.ElectricViewModels.AddRange(dataViews);

                                    List<OrtDataModel> datas = new List<OrtDataModel>();
                                    datas.AddRange(ViewModelTrans<OrtDataModel>.ElectricViewToData(headIds[i], snos[j], dataViews));
                                    dtl.Datas.Clear();
                                    dtl.Datas.AddRange(datas);
                                    if(datas != null && datas.Count>0)
                                    {
                                       if(datas.Where(t => t.Value > 0 && t.Valid == "2").Any()
                                            && (head.TestTime < head.TestTotalTime && head.TestTotalTime >0))
                                        {
                                            head.IsValid = false;
                                            head.Level = "C";
                                        }
                                    }
                                }

                                if (head != null) headGenReportList.Add(head);
                                
                            }

                            LockService.DelLock(db, _LockIds);

                            if(billNos.Count>0)
                            {
                                SysLogService.Log(db, this._User, this
                                    , tsmLcr_Double.Text
                                    , string.Join(",", billNos.ToArray()), string.Empty);

                                if(headGenReportList.Count > 0)
                                {
                                    headGenReportList.ForEach(t =>
                                    {
                                        AutoGenReport(t);
                                    });
                                }
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        Logger.LogError(ex);
                    }
                    finally
                    {
                        LockService.DelLock(db, _LockIds);
                    }
                }

                bool isTestting = false;
                List<Form> delForms = new List<Form>();
                foreach (Form f in SubFormList)
                {
                    var ff = f as IMachine;
                    if (ff != null && !ff.IsClosing)
                    {
                        isTestting = true;
                        ff.RefreshGrid();
                    }
                    else
                        delForms.Add(f);
                }

                if (delForms.Count > 0)
                {
                    foreach(Form f in delForms)
                    {
                        SubFormList.Remove(f);
                    }
                }

                delForms = null;
                if (!isTestting)
                    DtlDataGridView.Enabled = true;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            finally
            {
                ElectricDataGridView.Refresh();
            }
        }

        /// <summary>
        /// 容量变化率是否合格
        /// </summary>
        void IsValidCapRate()
        {
            //容量變化率是否合格
            if (_CurrentDtl.SNo > 1 && _FormStatus != FormStatus.Browser && _CurrentHead.CapRate>0)
            {
                try
                {
                    var firstDtls = _CurrentHead.Dtls.Where(d => d.SNo == 1);
                    if (firstDtls == null || firstDtls.Count() > 0)
                    {
                        var firstDtl = firstDtls.First();
                        double rate = _CurrentHead.CapRate;

                        for (int i = 0; i < firstDtl.ElectricViewModels.Count; i++)
                        {
                            if (_CurrentDtl.ElectricViewModels.Count - 1 < i) break;

                            _CurrentDtl.ElectricViewModels[i].CAPisValid =
                                (_CurrentDtl.ElectricViewModels[i].CAP >= firstDtl.ElectricViewModels[i].CAP * (1 - rate / 100))
                                && (_CurrentDtl.ElectricViewModels[i].CAP <= firstDtl.ElectricViewModels[i].CAP * (1 + rate / 100));
                        }
                    }
                }
                catch (Exception ex2)
                {
                    Logger.LogError(ex2);
                }
            }
        }

        bool isESCcancel = false;
        private void ElectricDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            try
            {
                if (_FormStatus == FormStatus.Browser) return;

                {
                    if (ElectricDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ValueType == typeof(Double)
                        || ElectricDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].ValueType == typeof(Decimal))
                    {
                        ElectricDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                        e.Cancel = true;
                        SendKeys.Send("{ESC}");
                        isESCcancel = true;
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void SizeDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void DtlDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;
            if (DtlDataGridView.CurrentCell == null) return;
            if (_CurrentDtl == null) return;

            try
            {
                //根據檢測時間計算到期日期
                
                decimal testTime = 0;
                if (DtlDataGridView.Columns[DtlDataGridView.CurrentCell.ColumnIndex] == Col_D_TestTime
                    || DtlDataGridView.Columns[DtlDataGridView.CurrentCell.ColumnIndex] == Col_D_TestDate
                    //&& (_CurrentHead.Dtls[_CurrentHead.Dtls.Count - 1] == _CurrentDtl)
                    )
                {
                    decimal.TryParse(DtlDataGridView.CurrentCell.Value.ToString(), out testTime);
                    if (testTime <= 0) return;

                    int preTime = 0;
                    var preDtls = _CurrentHead.Dtls.Where(t => t.SNo < _CurrentDtl.SNo);
                    if(preDtls.Any())
                    {
                        try
                        {
                            int maxPreSno = preDtls.Max(t => t.SNo);
                            preTime = preDtls.Where(t => t.SNo == maxPreSno).FirstOrDefault().TestTime;
                        }catch(Exception ex
                        )
                        {
                            Logger.LogError(ex);
                        }
                    }

                    _CurrentDtl.ExpireDate = FormCommon.GetExpireDate(_CurrentDtl.TestDate, testTime - preTime);
                    DtlDataGridView.Refresh();
                }

                //如果是最新的次數，則更新主表的到期日期
                OrtDtlModel m = _CurrentHead.Dtls.Find(t => t.SNo == _CurrentHead.Dtls.Max(t1 => t1.SNo));
                if (m == _CurrentDtl)
                {
                    _CurrentHead.TestTime = (int)testTime;
                    _CurrentHead.ExpireDate = _CurrentDtl.ExpireDate;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void txtSourceNo_KeyDown(object sender, KeyEventArgs e)
        {
     
        }

        /// <summary>
        /// 獲取工單备料档
        /// </summary>
        /// <param name="sfb01"></param>
        void GetSfaView(string sfb01)
        {
            if (string.IsNullOrWhiteSpace(sfb01)) return;
            string customerName = string.Empty;
            List<sfa_view> sfaList = null;
            //BackgroundWorker worker = new BackgroundWorker();
            //worker.DoWork += (s, a) => {
                try
                {
                    sfaList = ErpService.GetWoBom(dbContext, sfb01);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                }
            //};

            //worker.RunWorkerCompleted += (s, a) =>
            //{


                if (sfaList != null && sfaList.Count > 0)
                {
                    foreach (sfa_view sfa in sfaList)
                    {
                        //正箔
                        if (!sfa.sfa03.StartsWith("FB") && sfa.sfa03.StartsWith("F")
                            //&& s.sfa03.Length == MaterialCode.CuttedFoilpCodeCount
                            )
                            _CurrentHead.FoilP = sfa.sfa03;
                        //负箔
                        else if (sfa.sfa03.StartsWith("FB"))
                            _CurrentHead.FoilN = sfa.sfa03;
                        //电解纸
                        else if (sfa.sfa03.StartsWith("P"))
                            _CurrentHead.Eps = sfa.sfa03;
                        //导针
                        else if (sfa.sfa03.StartsWith("D")
                            //&& s.sfa03.Length == MaterialCode.LeadWireCodeCount
                            )
                            _CurrentHead.LeadWire = sfa.sfa03;
                        //铝壳
                        else if (sfa.sfa03.StartsWith("C")
                            //&& s.sfa03.Length == MaterialCode.AlCaseCodeCount
                            )
                            _CurrentHead.AlCase = sfa.sfa03;
                        //胶盖
                        else if (sfa.sfa03.StartsWith("B")
                            //&& s.sfa03.Length == MaterialCode.RubberCodeCount
                            )
                            _CurrentHead.Rubber = sfa.sfa03;
                        //电解液
                        else if (sfa.sfa03.StartsWith("W"))
                            _CurrentHead.Paste = sfa.sfa03;
                    }

                BindingControls();
            }
                
            //};

            //worker.RunWorkerAsync();
        }

        /// <summary>
        /// 獲取工單料號，客戶、客戶料號
        /// </summary>
        /// <param name="sfb01"></param>
        void GetSfbView(string sfb01)
        {
            if (string.IsNullOrWhiteSpace(sfb01)) return;
            string customerName = string.Empty;
            SfbView sfbView = null;

                try
                {
                    sfbView = ErpService.GetSfbView(dbContext, sfb01);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                }

                if (sfbView != null)
                {
                    if (!string.IsNullOrWhiteSpace(sfbView.occ02))
                    {
                        txtCustomer.Text = sfbView.occ02;
                        _CurrentHead.Customer = sfbView.occ02;
                    }
                    if (!string.IsNullOrWhiteSpace(sfbView.ta_sfb08))
                    {
                        _CurrentHead.CustomerCode = sfbView.ta_sfb08;
                    }

                    else
                    {
                        _CurrentHead.CustomerCode = string.Empty;
                    }
                    if (!string.IsNullOrWhiteSpace(sfbView.sfb05)) _CurrentHead.Pn = sfbView.sfb05;
                    else _CurrentHead.Pn = string.Empty;
                    if (!string.IsNullOrWhiteSpace(sfbView.ta_sfb07))
                        _CurrentHead.CustomerPn = sfbView.ta_sfb07;
                    else _CurrentHead.CustomerPn = string.Empty;
                }

                if (!string.IsNullOrWhiteSpace(_CurrentHead.Pn))
                {
                    _CurrentHead.Series = ProductCode.GetSeriesCode(_CurrentHead.Pn);
                    _CurrentHead.Cap = ProductCode.GetCap(_CurrentHead.Pn);
                    _CurrentHead.Voltage = ProductCode.GetVoltage(_CurrentHead.Pn);
                    _CurrentHead.Size = ProductCode.GetSize(_CurrentHead.Pn);
                }

                BindingControls();

        }

        /// <summary>
        /// 根據工單備註獲取客戶名稱
        /// </summary>
        /// <param name="sfw01">工單號</param>
        void GetCustomerNameBySfw01(string sfw01)
        {
            if(string.IsNullOrWhiteSpace(sfw01)) return;
            string customerName = string.Empty;

                try
                {
                    customerName = ErpService.GetCustomerNameBySfw(dbContext, sfw01);
                }
                catch(Exception ex)
                {
                    Logger.LogError(ex);
                }


           
                if (!string.IsNullOrWhiteSpace(customerName))
                {
                    txtCustomer.Text = customerName;
                    _CurrentHead.Customer = customerName;
                }

        }

        void GetStandard()
        {
            if (_CurrentHead == null) return;
            if (_FormStatus == FormStatus.Browser) return;

            //if (string.IsNullOrWhiteSpace(_CurrentHead.Pn)) return;

            try
            {
                #region mark
                string apiurl = SysParamService.GetSysParamValue(dbContext, "ApiUrl");
                if (string.IsNullOrEmpty(apiurl)) apiurl = "http://192.168.32.99";
                string url = apiurl + "/api/FQC_standard?workno=" + _CurrentHead.SourceNo;
                Logger.LogMessage(url);
                string data = "";
                try
                {
                    data = ApiHelper.HttpPost(url, string.Empty, "GET");
                }
                catch(Exception ex2)
                {
                    Logger.LogError(ex2);
                    QMessageBox.ShowException(ex2);
                }
#if DEBUG
                if (string.IsNullOrWhiteSpace(data))
                    data = "[{\"ItemName\":\"item_No\",\"Standard\":\"TL-1J212M6N1845BCE\"},{\"ItemName\":\"capMax\",\"Standard\":\"2520.0\"},{\"ItemName\":\"capMin\",\"Standard\":\"1701.00\"},{\"ItemName\":\"fqc_df\",\"Standard\":\"9.5\"},{\"ItemName\":\"fqc_lc\",\"Standard\":\"793.800\"},{\"ItemName\":\"fqc_impd\",\"Standard\":\"0.06\"},{\"ItemName\":\"fqc_esr\",\"Standard\":\"0.4\"},{\"ItemName\":\"fqc_heightMin\",\"Standard\":\"45\"},{\"ItemName\":\"fqc_heightMax\",\"Standard\":\"46.5\"},{\"ItemName\":\"fqc_diaMin\",\"Standard\":\"18\"},{\"ItemName\":\"fqc_diaMax\",\"Standard\":\"18.5\"},{\"ItemName\":\"fqc_No01\",\"Standard\":\"01050V105M036\"},{\"ItemName\":\"fqc_No02\",\"Standard\":\"10040P036\"},{\"ItemName\":\"fqc_No03\",\"Standard\":\"220236301L\"},{\"ItemName\":\"fqc_No04\",\"Standard\":\"220236250L\"},{\"ItemName\":\"fqc_No05\",\"Standard\":\"3NMR5D150039\"},{\"ItemName\":\"fqc_No06\",\"Standard\":\"\"},{\"ItemName\":\"fqc_No07\",\"Standard\":\"418050R0\"},{\"ItemName\":\"fqc_No08\",\"Standard\":\"5R18465E\"},{\"ItemName\":\"fqc_No09\",\"Standard\":\"6918PF\"},{\"ItemName\":\"fqc_No10\",\"Standard\":\"7KHP200A\"}]";
#endif
                Logger.LogMessage(url);
                OrtService.FqcApiData = data;
                if (!string.IsNullOrWhiteSpace(data))
                {
                    var data2 = data.Replace("\\\"", "\"").TrimStart('"').TrimEnd('"')
                        .Replace("NULL", "null");
                    var stds = data2.ToObject<List<ErpStdView>>();

                    if(stds != null && stds.Count>0)
                    {
                        #region 物料
                        var std1 = stds.Where(t => t.ItemName.ToLower() == "item_no").FirstOrDefault();
                        if (std1 != null)
                        {
                            _CurrentHead.Pn = std1.Standard;
                            if (!string.IsNullOrEmpty(_CurrentHead.Pn) && _CurrentHead.Pn.Length > 3)
                                _CurrentHead.Series = _CurrentHead.Pn.Substring(0, 3);
                        }
                        std1 = stds.Where(t => t.ItemName.ToLower() == "fqc_no01").FirstOrDefault();
                        if (std1 != null)
                            _CurrentHead.FoilP = std1.Standard;
                        std1 = stds.Where(t => t.ItemName.ToLower() == "fqc_no02").FirstOrDefault();
                        if (std1 != null)
                            _CurrentHead.FoilN = std1.Standard;
                        std1 = stds.Where(t => t.ItemName.ToLower() == "fqc_no03").FirstOrDefault();
                        if (std1 != null)
                            _CurrentHead.LeadWire = std1.Standard;
                        var std2 = stds.Where(t => t.ItemName.ToLower() == "fqc_no05").ToList();
                        if (std2 != null && std2.Count > 0)
                        {
                            string ss = string.Join(Environment.NewLine, std2.Select(t => t.Standard));
                            _CurrentHead.Eps = ss;
                        }
                        std1 = stds.Where(t => t.ItemName.ToLower() == "fqc_no07").FirstOrDefault();
                        if (std1 != null)
                            _CurrentHead.Rubber = std1.Standard;
                        std1 = stds.Where(t => t.ItemName.ToLower() == "fqc_no08").FirstOrDefault();
                        if (std1 != null)
                            _CurrentHead.AlCase = std1.Standard;
                        std1 = stds.Where(t => t.ItemName.ToLower() == "fqc_no10").FirstOrDefault();
                        if (std1 != null)
                            _CurrentHead.Paste = std1.Standard;
                        #endregion
                        #region 标准
                        if (_CurrentHead.BillType == "FQC")
                        {
                            double st = 0d;
                            var std = stds.Where(t => t.ItemName.ToUpper() == "CAPMAX").FirstOrDefault();
                            if (std != null)
                            {
                                if(double.TryParse(std.Standard, out st))
                                    _CurrentHead.Standard.CapMax = st;
                            }
                            std = stds.Where(t => t.ItemName.ToUpper() == "CAPMIN").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                    _CurrentHead.Standard.CapMin = st;
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_df").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.DfMax = st;
                                    _CurrentHead.DfMax = st;
                                    _CurrentHead.DfMaxAfter = st;
                                }
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_lc").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.LcMax = st;
                                    _CurrentHead.LcMax = st;
                                    _CurrentHead.LcMaxAfter = st;
                                }
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_impd").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.ZMax = st * 1000d;
                                    _CurrentHead.ZMax = st * 1000d;
                                }
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_esr").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.EsrMax = st*1000d;
                                    _CurrentHead.EsrMax = st * 1000d;
                                    _CurrentHead.EsrMaxAfter = st * 1000d;
                                }
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_heightmin").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.LMin = st;
                                }
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_heightmax").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.LMax = st;
                                    _CurrentHead.LMax = st;
                                }
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_diamin").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.DMin = st;
                                }
                            }
                            std = stds.Where(t => t.ItemName.ToLower() == "fqc_diamax").FirstOrDefault();
                            if (std != null)
                            {
                                if (double.TryParse(std.Standard, out st))
                                {
                                    _CurrentHead.Standard.DMax = st;
                                    _CurrentHead.DMax = st;
                                }
                            }
                        }
                        #endregion 标准
                    }
                }
                #endregion mark
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.ShowException(ex);
            }

            GetOldStandard();
        }
        void GetOldStandard()
        {
            if (_CurrentHead == null) return;
            if (_FormStatus == FormStatus.Browser) return;

            if (string.IsNullOrWhiteSpace(_CurrentHead.Pn)) return;

            try
            {
                OrtHeadModel oldHead = _OrtService.GetHead(_CurrentHead.Pn, _CurrentHead.CustomerPn,this._BillType, _CurrentHead.ReportId);
                if (oldHead == null) return;

                if (_CurrentHead.CapMax <= 0) _CurrentHead.CapMax = oldHead.CapMax;
                if (_CurrentHead.CapMin <= 0) _CurrentHead.CapMin = oldHead.CapMin;
                if (_CurrentHead.CapRate <= 0) _CurrentHead.CapRate = oldHead.CapRate;
                if (_CurrentHead.CapRate2 <= 0) _CurrentHead.CapRate2 = oldHead.CapRate2;
                if (_CurrentHead.cp <= 0) _CurrentHead.cp = oldHead.cp;
                if (_CurrentHead.DfMax <= 0) _CurrentHead.DfMax = oldHead.DfMax;
                if (_CurrentHead.DfMaxAfter <= 0) _CurrentHead.DfMaxAfter = oldHead.DfMaxAfter;
                if (_CurrentHead.EsrMax <= 0) _CurrentHead.EsrMax = oldHead.EsrMax;
                if (_CurrentHead.EsrMaxAfter <= 0) _CurrentHead.EsrMaxAfter = oldHead.EsrMaxAfter;
                if (_CurrentHead.LcMax <= 0) _CurrentHead.LcMax = oldHead.LcMax;
                if (_CurrentHead.LcMaxAfter <= 0) _CurrentHead.LcMaxAfter = oldHead.LcMaxAfter;
                if (_CurrentHead.LcMaxAfter <= 0) _CurrentHead.LcMaxAfter = oldHead.LcMax;
                if (_CurrentHead.ZMax <= 0) _CurrentHead.ZMax = oldHead.ZMax;
                if (_CurrentHead.ZRate <= 0) _CurrentHead.ZRate = oldHead.ZRate;
                if (_CurrentHead.ZRate2 <= 0) _CurrentHead.ZRate2 = oldHead.ZRate2;
                if (_CurrentHead.TestTotalTime <= 0) _CurrentHead.TestTotalTime = oldHead.TestTotalTime;
                if (_CurrentHead.WeightMax <= 0 && oldHead.WeightMax >=0) _CurrentHead.WeightMax = oldHead.WeightMax;

                if (oldHead.Cap >= 0) _CurrentHead.Cap = oldHead.Cap;
                if (oldHead.Voltage >= 0) _CurrentHead.Voltage = oldHead.Voltage;
                if (!string.IsNullOrWhiteSpace(oldHead.Series)) _CurrentHead.Series = oldHead.Series;
                if (!string.IsNullOrWhiteSpace(oldHead.Size)) _CurrentHead.Size = oldHead.Size;

                BindingControls();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        public void SetBillTypeDesc(string s)
        {
            tssCurrentId.Text = s;
        }

        public string GetBillTypeDesc()
        {
            string BillTypeDesc = string.Empty;
            try
            {
                BillTypeDesc = Tools.GetEnumDescription<OrtBillType>(_BillType);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }

            return BillTypeDesc;
        }

        private void MainDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }

        private void cboTestTarget_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Add && cboTestTarget.SelectedItem != null)
            {
                try
                {
                    var testTarget = (KeyValuePair<string, string>)cboTestTarget.SelectedItem;

                    if (this._BillType == "LDT")
                    {
                        if (testTarget.Value == "In-material test"
                            && !string.IsNullOrWhiteSpace(_CurrentHead.BillNo)
                            && _CurrentHead.BillNo.StartsWith("LDT")
                        )
                        {
                            _CurrentHead.BillNo = _CurrentHead.BillNo.Replace("LDT", "LDW");
                            txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, false);
                        }
                        else if (testTarget.Value != "In-material test"
                            && !string.IsNullOrWhiteSpace(_CurrentHead.BillNo)
                            && _CurrentHead.BillNo.StartsWith("LDW"))
                        {
                            _CurrentHead.BillNo = _CurrentHead.BillNo.Replace("LDW", "LDT");
                            txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, false);
                        }
                    }
                    else if (this._BillType == "SFLDT")
                    {
                        if (testTarget.Value == "In-material test"
                            && !string.IsNullOrWhiteSpace(_CurrentHead.BillNo)
                            && _CurrentHead.BillNo.StartsWith("SFLDT")
                        )
                        {
                            _CurrentHead.BillNo = _CurrentHead.BillNo.Replace("SFLDT", "SFLDW");
                            txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, false);
                        }
                        else if (testTarget.Value != "In-material test"
                            && !string.IsNullOrWhiteSpace(_CurrentHead.BillNo)
                            && _CurrentHead.BillNo.StartsWith("SFLDW"))
                        {
                            _CurrentHead.BillNo = _CurrentHead.BillNo.Replace("SFLDW", "SFLDT");
                            txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, false);
                        }
                    }
                }
                catch(Exception ex)
                {
                    Logger.LogError(ex);
                }
            }
        }

        private void FormOrt_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    if (this.ActiveControl == txtRemark) return;
                    if (this.ActiveControl == txtEps) return;
                    if (this.ActiveControl != txtSourceNo) e.Handled = true;
                    this.SelectNextControl(this.ActiveControl, true, true, true, true);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void txtSeries_Validated(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser || _FormStatus == FormStatus.Copy) return;

            try
            {
                //根据系列取CAP上下限
                if (Math.Abs(_CurrentHead.CapMax) == Math.Abs(_CurrentHead.CapMin) &&
                    (_CurrentHead.CapMax == 20 || _CurrentHead.CapMax == 0)
                    )
                {
                    double capMax,capMin;
                    if(_OrtService.GetLastCapRateBySeries(txtSeries.Text ,out capMax,out capMin))
                    {
                        txtCapMax.Text = capMax.ToString();
                        txtCapMin.Text = capMin.ToString();
                        _CurrentHead.CapMax = capMax;
                        _CurrentHead.CapMin = capMin;
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }

            //if (_BillType != "A" && _BillType != "SF") return;
            //if (_CurrentHead == null || string.IsNullOrWhiteSpace(_CurrentHead.Series))
            //    return;

            //try
            //{
            //    Regex re = new Regex(@"[a-zA-Z]+");
            //    Match m = re.Match(_CurrentHead.BillNo);
            //    _CurrentHead.BillNo = _CurrentHead.BillNo.Replace(m.Value, _CurrentHead.Series);
            //    txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, false);
            //}
            //catch(Exception ex)
            //{
            //    Logger.LogError(ex);
            //}
        }

        private void txtCustomer_Validated(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;
            if (_CurrentHead == null) return;

            //if(string.IsNullOrWhiteSpace(_CurrentHead.CustomerCode) && !string.IsNullOrWhiteSpace(_CurrentHead.CustomerCode))
            //{
            //    string customerCode = ErpService.GetCustomerCodeLikeName(dbContext, _CurrentHead.Customer);
            //    if(!string.IsNullOrWhiteSpace(customerCode))
            //    {
            //        _CurrentHead.CustomerCode = customerCode;
            //    }
            //}
        }

        private void cmsImoprt_Click(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;

            if (_CurrentHead == null) return;
            if(_CurrentHead.Dtls == null || _CurrentHead.Dtls.Count == 0)
            {
                QMessageBox.Show(LanguageHelper.GetLanguageText("請先新增测试次数！")
                    , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (_CurrentDtl == null) return;

            if (_CurrentHead.ReportId <= 0)
            {
                QMessageBox.Show(LanguageHelper.GetLanguageText("請先選擇報表模板！")
                    , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }


            if (QMessageBox.Show(LanguageHelper.GetLanguageText("導入將會覆蓋現有檢測數據，是否繼續？")
                , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OKCancel,MessageBoxIcon.Question) 
                == DialogResult.Cancel)
                return;


            #region 导入测试数据
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.Filter = "Excel2003|.xls|Excel2007|.xlsx";
            if (openFileDialog.ShowDialog() != DialogResult.OK) return;
            string fileName = openFileDialog.FileName;
            DataTable table = null;
            try
            {
                table = NPOIHelper.ExcelToDataTable(fileName);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
            if(table == null) {
                QMessageBox.Show("Excel格式錯誤，請檢查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (table.Rows.Count == 0)
            {
                QMessageBox.Show("沒有可導入的數據行！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            bool success = true;

            try
            {
                _CurrentDtl.GenerateList(_CurrentHead.ElectricQty, _CurrentHead.SizeQty, _CurrentDtl.SNo);
                string reportCode = GetReportCode(_CurrentHead.ReportId);
                _OrtService.GenStandard(_CurrentHead, _CurrentDtl, reportCode);
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (i < _CurrentDtl.ElectricViewModels.Count)
                    {
                        if (table.Columns.Contains("CAP(μF)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["CAP(μF)"].ToString(), out cap))
                            {
                                _CurrentDtl.ElectricViewModels[i].CAP = cap;
                                _CurrentDtl.ElectricViewModels[i].CAPisValid = _CurrentHead.Standard.IsValid(ItemCode.CAP, cap);
                            }
                        }
                        if (table.Columns.Contains("DF(%)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["DF(%)"].ToString(), out cap))
                            {
                                _CurrentDtl.ElectricViewModels[i].DF = cap;
                                _CurrentDtl.ElectricViewModels[i].DFisValid = _CurrentHead.Standard.IsValid(ItemCode.DF, cap);
                            }
                        }
                        if (table.Columns.Contains("LC(μA)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["LC(μA)"].ToString(), out cap))
                            {
                                _CurrentDtl.ElectricViewModels[i].LC = cap;
                                _CurrentDtl.ElectricViewModels[i].LCisValid = _CurrentHead.Standard.IsValid(ItemCode.LC, cap);
                            }
                        }
                        if (table.Columns.Contains("Z(mΩ)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["Z(mΩ)"].ToString(), out cap))
                            {
                                _CurrentDtl.ElectricViewModels[i].Z = cap;
                                _CurrentDtl.ElectricViewModels[i].ZisValid = _CurrentHead.Standard.IsValid(ItemCode.Z, cap);
                            }
                        }
                        if (table.Columns.Contains("ESR(mΩ)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["ESR(mΩ)"].ToString(), out cap))
                            {
                                _CurrentDtl.ElectricViewModels[i].ESR = cap;
                                _CurrentDtl.ElectricViewModels[i].ESRisValid = _CurrentHead.Standard.IsValid(ItemCode.ESR, cap);
                            }
                        }
                        if (table.Columns.Contains("High"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["High"].ToString(), out cap))
                            {
                                if (cap > 0)
                                {
                                    _CurrentDtl.ElectricViewModels[i].H = cap;
                                    _CurrentDtl.ElectricViewModels[i].HisValid = true;
                                }
                            }
                        }

                        if (table.Columns.Contains("Weight"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["Weight"].ToString(), out cap))
                            {
                                if (cap > 0)
                                {
                                    _CurrentDtl.ElectricViewModels[i].L1 = cap.ToString();
                                    _CurrentDtl.ElectricViewModels[i].L1isValid = true;
                                }
                            }
                            else
                            {
                                string ss = table.Rows[i]["Weight"].ToString();
                                if (!string.IsNullOrWhiteSpace(ss) && ss.Length<=10)
                                {
                                    _CurrentDtl.ElectricViewModels[i].L1 = ss;
                                }
                            }
                        }

                        if (table.Columns.Contains("D(mm)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["D(mm)"].ToString(), out cap))
                            {
                                if (cap > 0)
                                {
                                    _CurrentDtl.ElectricViewModels[i].D = cap;
                                    _CurrentDtl.ElectricViewModels[i].DisValid = true;
                                }
                            }
                        }

                        if (table.Columns.Contains("L(mm)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["L(mm)"].ToString(), out cap))
                            {
                                if (cap > 0)
                                {
                                    _CurrentDtl.ElectricViewModels[i].L = cap;
                                    _CurrentDtl.ElectricViewModels[i].LisValid = true;
                                }
                            }
                        }

                        if (table.Columns.Contains("F(mm)"))
                        {
                            double cap = 0;
                            if (double.TryParse(table.Rows[i]["F(mm)"].ToString(), out cap))
                            {
                                if (cap > 0)
                                {
                                    _CurrentDtl.ElectricViewModels[i].C = cap;
                                    _CurrentDtl.ElectricViewModels[i].CisValid = true;
                                }
                            }
                        }
                    }
                }

                ElectricDataGridView.DataSource = new BindingList<ElectricViewModel>(_CurrentDtl.ElectricViewModels);
                //SizeDataGridView.DataSource = new BindingList<SizeViewModel>(_CurrentDtl.SizeViewModels);

                QMessageBox.Show("导入成功", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "异常901", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            #endregion 导入测试数据
        }

        private void cmsExport_Click(object sender, EventArgs e)
        {
            //SaveFileDialog saveFileDialog = new SaveFileDialog();
            //saveFileDialog.Filter = "Excel2003|.xls|Excel2007|.xlsx";
            //if (saveFileDialog.ShowDialog() != DialogResult.OK) return;

            try
            {
                string fileName = NPOIHelper.DataGridViewToExcel("OrtExport",ElectricDataGridView
                    , ElectricDataGridView.DefaultCellStyle.Font.Name
                    , Convert.ToInt16(ElectricDataGridView.DefaultCellStyle.Font.Size)
                    ,true,string.Empty);

                if (File.Exists(fileName))
                    Process.Start(fileName);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("异常902")
                    , MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtNoDisplayZero_TextChanged(object sender, EventArgs e)
        {
            try
            {
                FormCommon.TextBoxNoDisplayZero_TextChanged(_CurrentHead, sender, e);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void MainDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (_FormStatus != FormStatus.Browser) return;
                if (MainDataGridView.Rows.Count <= 0) return;
                if (_Heads == null || _Heads.Count ==0) return;

                MainSort = MainSort == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
                //MainDataGridView.Sort(MainDataGridView.Columns[e.ColumnIndex], MainSort);
                ////_Heads.OrderBy(t => t.BillNo, );

                int i = MainSort == ListSortDirection.Ascending ? -1 : 1;
                //int i = MainSort == ListSortDirection.Ascending ? -1 : 1;
                string proName = MainDataGridView.Columns[e.ColumnIndex].DataPropertyName;
                if (proName == "BillNo")
                    _Heads.Sort((x, y) => { return  i * x.BillNo.CompareTo(y.BillNo); });
                else if(proName == "TestDate")
                    _Heads.Sort((x, y) => { return i * x.TestDate.CompareTo(y.TestDate); });
                else if (proName == "SourceNo")
                    _Heads.Sort((x, y) => { return i * x.SourceNo.CompareTo(y.SourceNo); });
                else if (proName == "Series")
                    _Heads.Sort((x, y) => { return i * x.Series.CompareTo(y.Series); });
                else if (proName == "Customer")
                    _Heads.Sort((x, y) => { return i * x.Customer.CompareTo(y.Customer); });
                else if (proName == "Cap")
                    _Heads.Sort((x, y) => { return i * x.Cap.CompareTo(y.Cap); });
                else if (proName == "Voltage")
                    _Heads.Sort((x, y) => { return i * x.Voltage.CompareTo(y.Voltage); });
                else if (proName == "Size")
                    _Heads.Sort((x, y) => { return i * x.Size.CompareTo(y.Size); });
                else if (proName == "Pn")
                    _Heads.Sort((x, y) => { return i * x.Pn.CompareTo(y.Pn); });
                else if (proName == "Remark")
                    _Heads.Sort((x, y) => { return i * x.Remark.CompareTo(y.Remark); });
                else if (proName == "ReportId")
                    _Heads.Sort((x, y) => { return i * x.ReportId.CompareTo(y.ReportId); });
                else if (proName == "ModiDate")
                    _Heads.Sort((x, y) => {
                        if (x.ModiDate.HasValue && y.ModiDate.HasValue)
                            return i * x.ModiDate.Value.CompareTo(y.ModiDate.Value);
                        else if (x.ModiDate.HasValue && !y.ModiDate.HasValue)
                            return i;
                        else if (!x.ModiDate.HasValue && y.ModiDate.HasValue)
                            return -i;
                        else return 0;
                    });
                else if (proName == "FinishDate")
                    _Heads.Sort((x, y) => {
                            return i * x.FinishDate.CompareTo(y.FinishDate);
                    });
                //else if (proName == "ExpireDate.")
                else if (proName == "ExpireDate")
                            _Heads.Sort((x, y) => {
                                if (x.ExpireDate.HasValue && y.ExpireDate.HasValue)
                                    return i * x.ExpireDate.Value.CompareTo(y.ExpireDate.Value);
                                else if (x.ExpireDate.HasValue && !y.ExpireDate.HasValue)
                                    return i;
                                else if (!x.ExpireDate.HasValue && y.ExpireDate.HasValue)
                                    return -i;
                                else return 0;
                            });

                MainDataGridView.DataSource = new BindingList<OrtHeadModel>(_Heads);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void ElectricDataGridView_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        //複製
        private void tsmCopy2_Click(object sender, EventArgs e)
        {

            if (!UserRightService.CheckRight(this, this._User, RightType.Add))
            {
                return;
            }
            try
            {
                if (tabControl.SelectedTab != tabDtl)
                {
                    tabControl.SelectedTab = tabDtl;
                }
                _FormStatus = FormStatus.Copy;
                _CurrentHead = _OrtService.Clone(_CurrentHead);
                _CurrentHead.Id = 0;
                _CurrentHead.TestDate = this._User.GetServerTime();
                _CurrentHead.CreateDate = this._User.GetServerTime();
                _CurrentHead.CreateUser = this._User.UserName;
                txtBillNo.Text = _OrtService.GetBillNo(_CurrentHead, true);
                //_CurrentHead.TestVoltage = 0;
                DateTime finishdate = DateTime.Now;
                DateTime.TryParse("2099-12-31", out finishdate);
                _CurrentHead.FinishDate = finishdate;


                if (_CurrentHead.Dtls != null && _CurrentHead.Dtls.Count > 0)
                    _CurrentHead.Dtls.Clear();
                DtlDataGridView.DataSource = new BindingList<OrtDtlModel>(_CurrentHead.Dtls);
                DtlDataGridView_RowEnter(DtlDataGridView, null);
                //_LockIds.Add(LockService.Lock(dbContext, _User, this, _CurrentHead.Id.ToString(), _CurrentHead.BillNo));
                BindingControls();
                SetControlsEnable();
                tssCurrentId.Text = string.Empty;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("異常S0023"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                _FormStatus = FormStatus.Browser;
                SetControlsEnable();
            }
        }

        private void txtPn_Validated(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;
            if (_CurrentHead == null) return;
            if (string.IsNullOrWhiteSpace(txtPn.Text))return;

            try
            {
                //if (_CurrentHead.Cap <= 0) _CurrentHead.Cap = ProductCode.GetCap(txtPn.Text);
                //if (_CurrentHead.Voltage <= 0) _CurrentHead.Voltage = ProductCode.GetVoltage(txtPn.Text);
                //if (string.IsNullOrWhiteSpace(_CurrentHead.Size)) _CurrentHead.Size = ProductCode.GetSize(txtPn.Text);

                GetOldStandard();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void tabControl_Selected(object sender, TabControlEventArgs e)
        {
            if (isAfterAdd)
            {
                MainDataGridView.DataSource = new BindingList<OrtHeadModel>(_Heads);
                isAfterAdd = false;
            }
        }

        string GetReportCode(int reportId)
        {
            if (reportId <= 0) return string.Empty;

            string reportCode = string.Empty;
            if(_ReportSetModels != null && _ReportSetModels.Count >0)
            {
                try
                {
                    ReportSetModel m = _ReportSetModels.Where(t => t.Id == reportId).FirstOrDefault();
                    if (m != null)
                        reportCode = m.Code;
                }
                catch(Exception ex)
                {
                    Logger.LogError(ex);
                }
            }

            return reportCode;
        }

        private void cmsSetCellValid_Click(object sender, EventArgs e)
        {
            try
            {
                if (_FormStatus == FormStatus.Browser) return;
                if (ElectricDataGridView.Rows.Count == 0) return;
                if (ElectricDataGridView.CurrentCell == null) return;
                DataGridViewColumn column =
                    ElectricDataGridView.Columns[ElectricDataGridView.CurrentCell.ColumnIndex];
                if (column == null) return;
                if (_CurrentDtl == null) return;

                bool flag = true;
                if (sender == cmsSetCellUnValid)
                    flag = false;

                ElectricViewModel model = ElectricDataGridView.CurrentRow.DataBoundItem as ElectricViewModel;
                if (model == null) return;
                if (column == Col_Cap)
                    model.CAPisValid = flag;
                else if (column == Col_DF)
                    model.DFisValid = flag;
                else if (column == Col_LC)
                    model.LCisValid = flag;
                else if (column == Col_Esr)
                    model.ESRisValid = flag;
                else if (column == Col_Z)
                    model.ZisValid = flag;
                else if (column == Col_L)
                    model.LisValid = flag;
                else if (column == Col_L1)
                    model.L1isValid = flag;
                else if (column == Col_D)
                    model.DisValid = flag;
                else if (column == Col_F)
                    model.CisValid = flag;

                ElectricDataGridView.Refresh();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void cmsSetColumnValid_Click(object sender, EventArgs e)
        {
            try
            {
                if (_FormStatus == FormStatus.Browser) return;
                if (ElectricDataGridView.Rows.Count == 0) return;
                if (ElectricDataGridView.CurrentCell == null) return;
                DataGridViewColumn column =
                    ElectricDataGridView.Columns[ElectricDataGridView.CurrentCell.ColumnIndex];
                if (column == null) return;

                bool flag = true;
                if (sender == cmsSetColumnUnValid)
                    flag = false;

                if (_CurrentDtl == null) return;
                if (column == Col_Cap)
                    _CurrentDtl.ElectricViewModels.ForEach(t=>t.CAPisValid = flag);
                else if (column == Col_DF)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.DFisValid = flag);
                else if (column == Col_LC)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.LCisValid = flag);
                else if (column == Col_Esr)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.ESRisValid = flag);
                else if (column == Col_Z)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.ZisValid = flag);
                else if (column == Col_L)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.LisValid = flag);
                else if (column == Col_L1)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.L1isValid = flag);
                else if (column == Col_D)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.DisValid = flag);
                else if (column == Col_F)
                    _CurrentDtl.ElectricViewModels.ForEach(t => t.CisValid = flag);

                ElectricDataGridView.Refresh();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }
        private void cmsDelRow_Click(object sender, EventArgs e)
        {
            try
            {
                if (_FormStatus == FormStatus.Browser) return;
                if (ElectricDataGridView.Rows.Count == 0) return;
                if (ElectricDataGridView.CurrentRow == null) return;
                if (_CurrentDtl == null) return;
                if (_CurrentHead == null) return;

                ElectricViewModel model = ElectricDataGridView.CurrentRow.DataBoundItem as ElectricViewModel;
                if (model != null && _CurrentDtl.ElectricViewModels.Contains(model)) 
                    _CurrentDtl.ElectricViewModels.Remove(model);

                ElectricDataGridView.Refresh();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void ElectricDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (_FormStatus == FormStatus.Browser) return;
                ElectricViewModel view = this.ElectricDataGridView.CurrentRow.DataBoundItem as ElectricViewModel;
                if (view == null) return;

                double value = 0;
                if (ElectricDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null) return;
                double.TryParse(ElectricDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out value);

                if (this.ElectricDataGridView.Columns[e.ColumnIndex] == Col_Cap)
                {
                    view.CAPisValid = _CurrentHead.Standard.IsValid(ItemCode.CAP, value);
                }
                else if (this.ElectricDataGridView.Columns[e.ColumnIndex] == Col_DF)
                {
                    if (view.SNo > 1 && _CurrentHead.DfMaxAfter > 0)
                        view.DFisValid = value <= _CurrentHead.DfMaxAfter;
                    else
                        view.DFisValid = _CurrentHead.Standard.IsValid(ItemCode.DF, value);
                }
                else if (this.ElectricDataGridView.Columns[e.ColumnIndex] == Col_LC)
                {
                    view.LCisValid = _CurrentHead.Standard.IsValid(ItemCode.LC, value);
                }
                //else if (this.ElectricDataGridView.Columns[e.ColumnIndex] == ColLc2)
                //{
                //    if (value > _CurrentHead.Standard.LcMax) view.LC2isValid = false;
                //    else view.LC2isValid = true;
                //}
                else if (this.ElectricDataGridView.Columns[e.ColumnIndex] == Col_Esr)
                {
                    if (_CurrentHead.EsrMaxAfter > 0)
                        view.ESRisValid = value <= _CurrentHead.EsrMaxAfter;
                    else if (_CurrentHead.EsrMax > 0)
                        view.ESRisValid = value <= _CurrentHead.EsrMax;
                    else
                        view.ESRisValid = true;
                }
                else if (this.ElectricDataGridView.Columns[e.ColumnIndex] == Col_ESR2)
                {
                    if (_CurrentHead.EsrMaxAfter > 0)
                        view.ESR2isValid = value <= _CurrentHead.EsrMaxAfter;
                    else if (_CurrentHead.EsrMax > 0)
                        view.ESR2isValid = value <= _CurrentHead.EsrMax;
                    else
                        view.ESR2isValid = true;
                }
                else if (this.ElectricDataGridView.Columns[e.ColumnIndex] == Col_Z)
                {
                    if (_CurrentHead.ZMax > 0)
                        view.ZisValid = value <= _CurrentHead.ZMax;
                    else
                        view.ZisValid = true;
                }
                else if (this.ElectricDataGridView.Columns[e.ColumnIndex] == Col_Z2)
                {
                    if (_CurrentHead.ZMax > 0)
                        view.Z2isValid = value <= _CurrentHead.ZMax;
                    else
                        view.Z2isValid = true;
                }

                if (view.SNo > 1)
                {
                    IsValidCapRate();
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void ElectricDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

        }

        private void ElectricDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;
            try
            {
                if (isESCcancel)
                {
                    isESCcancel = false;
                    if (e.RowIndex < ElectricDataGridView.Rows.Count - 1)
                    {

                        ElectricDataGridView.CurrentCell = ElectricDataGridView.Rows[e.RowIndex + 1].Cells[e.ColumnIndex];
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        //数据转移
        private void tsmTranToBillDtl_Click(object sender, EventArgs e)
        {
            if (_FormStatus != FormStatus.Browser) return;
            if (_CurrentHead == null || _CurrentDtl == null) return;

            try
            {
                if(_CurrentDtl.ElectricViewModels.Count<= _CurrentHead.ElectricQty
                    || _CurrentDtl.ElectricViewModels.Count<=0)
                {
                    QMessageBox.Show(LanguageHelper.GetLanguageText("没有可转移的数据")
                        , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                FormTranData f = new FormTranData(_CurrentHead, _CurrentDtl.SNo
                    , _User, _BillType, _ReportSetModels
                    ,_OrtService
                    );
                if (f.ShowDialog() != DialogResult.OK) return;

                string targetBillNo = f.TargetBillNo;
                int targetSNo = f.TargetSNo;
                if (string.IsNullOrWhiteSpace(targetBillNo))
                {
                    QMessageBox.Show(LanguageHelper.GetLanguageText("目标单号不能为空")
                        , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (targetSNo <= 0)
                {
                    QMessageBox.Show(LanguageHelper.GetLanguageText("目标次数必须大于0")
                        , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                OrtHeadModel targetHead = _OrtService.GetHeadByBillNo(targetBillNo);
                if(targetHead ==null || targetHead.Id<=0)
                {
                    QMessageBox.Show(LanguageHelper.GetLanguageText("目标单号不存在; ")+ targetBillNo
                        , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                List<OrtDataModel> tartDatas = _OrtService.GetDatas(targetHead.Id, targetSNo);
                if (tartDatas == null || tartDatas.Count>0)
                {
                    QMessageBox.Show(LanguageHelper.GetLanguageText("目标单号对应的测试次数已有数据，不能转移; ") + targetBillNo
                        , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                string msg = string.Empty;
                if(_OrtService.TranDataToOtherDtl(_CurrentHead,_CurrentDtl,targetHead, targetSNo,out msg))
                {
                    //ElectricDataGridView.Refresh();
                    ElectricDataGridView.DataSource = new BindingList<ElectricViewModel>(_CurrentDtl.ElectricViewModels);

                    QMessageBox.Show(LanguageHelper.GetLanguageText("数据转单成功") + targetBillNo
                            ,LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Information);

                    //刷新目标单据界面数据
                    if(_Heads.Where(t=>t.BillNo == targetBillNo).Any())
                    {
                        var tartBill = _Heads.Where(t => t.BillNo == targetBillNo).First();
                        tartBill.Dtls = _OrtService.GetDtls(tartBill.Id);
                    }

                    SysLogService.Log(dbContext, this._User, this
                        , _FormStatus == FormStatus.Edit ? tsmEdit.Text : tsmAdd.Text
                        , _CurrentHead.BillNo + "->" + targetBillNo, LanguageHelper.GetLanguageText("转单：") + _CurrentDtl.ToJson());
                }
                else
                {
                    if(!string.IsNullOrWhiteSpace(msg))
                    {
                        QMessageBox.Show(LanguageHelper.GetLanguageText(msg) + targetBillNo
                            ,LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message
                            , LanguageHelper.GetLanguageText("提示"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtDfMax_Validated(object sender, EventArgs e)
        {
            try
            {
                string reportCode = GetReportCode(_CurrentHead.ReportId);
                if (_CurrentHead.DfMax > 0)
                {
                    if (reportCode == "R001" || reportCode == "R002")
                    {
                        _CurrentHead.DfMaxAfter = 2 * _CurrentHead.DfMax;
                    }
                    else if (reportCode == "R005")
                        _CurrentHead.DfMaxAfter = 1.2 * _CurrentHead.DfMax;
                    else
                    {
                        var h = _OrtService.GetHead(this._BillType, _CurrentHead.ReportId);
                        if(h != null && h.DfMax>0 && h.DfMax != h.DfMaxAfter)
                        _CurrentHead.DfMaxAfter = Math.Round(_CurrentHead.DfMax * (h.DfMaxAfter/h.DfMax),2);
                        else _CurrentHead.DfMaxAfter = _CurrentHead.DfMax;
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void txtSourceNo_Validated(object sender, EventArgs e)
        {
            if (_FormStatus != FormStatus.Add) return;
            if (_CurrentHead == null) return;
            {
                if (string.IsNullOrWhiteSpace(txtSourceNo.Text)) return;
                if (txtSourceNo.Text.Length < 5) return;

                try
                {
                    string sfb01 = _CurrentHead.SourceNo;
                    if (string.IsNullOrWhiteSpace(_CurrentHead.LotNo))
                        _CurrentHead.LotNo = _CurrentHead.SourceNo;
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    QMessageBox.Show(ex.Message, LanguageHelper.GetLanguageText("异常S0701")
                        , MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                GetStandard();

                BindingControls();
            }
        }

        private void cboReport_Validated(object sender, EventArgs e)
        {
            try
            {
                if (_FormStatus == FormStatus.Browser) return;

                ReportSetModel model = cboReport.SelectedItem as ReportSetModel;
                if (model != null && _CurrentHead != null)
                {
                    //if (model != null && model.Id != _CurrentHead.ReportId)
                    {
                        if (model.ElectricQty > 0) _CurrentHead.ElectricQty = model.ElectricQty;
                        if (model.SizeQty > 0) _CurrentHead.SizeQty = model.SizeQty;

                        if (_CurrentHead.SizeQty == 0) _CurrentHead.SizeQty = _CurrentHead.ElectricQty;
                        if (_CurrentHead.ElectricQty == 0) _CurrentHead.ElectricQty = _CurrentHead.SizeQty;

                        if (model.ElectricQty <= 0 && model.SizeQty > 0) _CurrentHead.ElectricQty = model.SizeQty;
                    }

                    if (model != null)
                    {
                        Col_ESR2.Visible = model.HasEsr2;
                        Col_Z2.Visible = model.HasZ2;
                    }

                    if (model.Code == "R003")
                    {
                        _CurrentHead.TestTemp = 260;
                        _CurrentHead.CapRate = 10;
                    }
                    else if (model.Code == "R004")
                    {
                        _CurrentHead.TestTemp = 235;
                        _CurrentHead.CapRate = 10;
                    }
                    else if (model.Code == "R005")
                    {
                        _CurrentHead.TestTotalTime = 240;
                        _CurrentHead.TestTemp = 40;
                        _CurrentHead.TestHumidity = 90;
                        _CurrentHead.CapRate = 10;
                    }
                    else if (model.Code == "R006")
                    {
                        _CurrentHead.TestTemp = -40;
                        _CurrentHead.CapRate = 10;
                        _CurrentHead.TestTotalTime = 72;
                    }
                    else if (model.Code == "R007")
                    {
                        _CurrentHead.CapRate = 5;
                    }
                    else if (model.Code == "R012") //12涌浪电压
                    {
                        _CurrentHead.CapRate = 15;
                        _CurrentHead.TestTemp = 105;
                        if (_CurrentHead.Voltage == 160)
                            _CurrentHead.TestVoltage = 180;
                        else if (_CurrentHead.Voltage == 250)
                            _CurrentHead.TestVoltage = 290;
                        else if (_CurrentHead.Voltage == 6.3)
                            _CurrentHead.TestVoltage = 7.2;
                        else if (_CurrentHead.Voltage <= 315)
                            _CurrentHead.TestVoltage = Math.Round(_CurrentHead.Voltage * 1.15, 0);

                        _CurrentHead.TestTotalTime = 1000;
                    }
                    else if (model.Code == "R013") //13充放電
                    {
                        _CurrentHead.TestTemp = 105;
                        _CurrentHead.TestTotalTime = 10000;
                        if (_CurrentHead.Voltage > 0)
                            _CurrentHead.TestVoltage = _CurrentHead.Voltage;
                    }
                    else if (model.Code == "R014")
                    {
                        _CurrentHead.TestTotalTime = 500;
                    }

                    SetAfterStandard();

                    BindingControls();
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 根据报表类型设置默认的试验后标准
        /// </summary>
        void SetAfterStandard()
        {
            try
            {
                string reportCode = string.Empty;
                if (_CurrentHead != null) reportCode = GetReportCode(_CurrentHead.ReportId);

                if (reportCode == "R021")
                {
                    splitContainer1.Panel2Collapsed = false;
                    splitContainer1.SplitterDistance = (int)(splitContainer1.Width * 0.4);
                    if (_CurrentHead != null && _CurrentHead.Volts.Count == 0)
                    {
                        _CurrentHead.GenVolts();
                        VDataGridView.DataSource = new BindingList<OrtVoltageModel>(_CurrentHead.Volts);
                    }

                    SetVoltsHeadText();
                }
                else
                {
                    splitContainer1.Panel2Collapsed = true;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        void SetVoltsHeadText()
        {
            try
            {
                double v = 0;
                if (_CurrentHead != null) v = _CurrentHead.Voltage;
                Col_V_V1.HeaderText = "0.5h(" + v.ToString() + "V)";
                Col_V_V2.HeaderText = "1h(" + Math.Round(v * 1.2, 2).ToString() + "V)";
                Col_V_V3.HeaderText = "1.5h(" + Math.Round(v * 1.4, 2).ToString() + "V)";
                Col_V_V4.HeaderText = "2h(" + Math.Round(v * 1.6, 2).ToString() + "V)";
                Col_V_V5.HeaderText = "2.5h(" + Math.Round(v * 1.6, 2).ToString() + "V)";
                Col_V_V6.HeaderText = "3h(" + Math.Round(v * 2, 2).ToString() + "V)";
                Col_V_V7.HeaderText = "3.5h(" + Math.Round(v * 2.2, 2).ToString() + "V)";
                Col_V_V8.HeaderText = "4h(" + Math.Round(v * 2.4, 2).ToString() + "V)";
                Col_V_V9.HeaderText = "4.5h(" + Math.Round(v * 2.6, 2).ToString() + "V)";
                Col_V_V10.HeaderText = "5h(" + Math.Round(v * 2.8, 2).ToString() + "V)";
                Col_V_V11.HeaderText = "5.5h(" + Math.Round(v * 3, 2).ToString() + "V)";
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        private void txtEsrMax_Validated(object sender, EventArgs e)
        {
            SetAfterStandard();
        }

        private void VDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            
        }

        /// <summary>
        /// 耐压网格填充值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsmFill_Click(object sender, EventArgs e)
        {
            try
            {
                if (VDataGridView.Rows.Count < 2) return;
                if (VDataGridView.CurrentCell != null)
                {
                    int colmnIndex = VDataGridView.CurrentCell.ColumnIndex;

                    if (VDataGridView.CurrentCell.Value == null) return;
                    if (string.IsNullOrWhiteSpace(VDataGridView.CurrentCell.Value.ToString())) return;
                    for (int i = VDataGridView.CurrentCell.RowIndex + 1; i < VDataGridView.Rows.Count; i++)
                    {
                        if (i >= VDataGridView.Rows.Count) break;
                        VDataGridView.Rows[i].Cells[colmnIndex].Value =
                            VDataGridView.CurrentCell.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0036_Fill", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void lblFoilN_Click(object sender, EventArgs e)
        {

        }

        private void txtLcMax_Validated(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;
            try
            {
                if (_CurrentHead.LcMaxAfter == 0)
                    _CurrentHead.LcMaxAfter = _CurrentHead.LcMax;

                var reportSet = _ReportSetModels.Where(t => t.Id == _CurrentHead.ReportId).FirstOrDefault();
                if(reportSet != null && reportSet.Code == "R002")
                    _CurrentHead.LcMaxAfter = _CurrentHead.LcMax*2;
            }
            catch(Exception ex)
            {
                QMessageBox.ShowException1(ex);
            }
        }

        private void txtVoltage_Validated(object sender, EventArgs e)
        {
            if (_FormStatus == FormStatus.Browser) return;
            try
            {
                var reportSet = _ReportSetModels.Where(t => t.Id == _CurrentHead.ReportId).FirstOrDefault();
                if (reportSet != null && _CurrentHead.Voltage >0 && (reportSet.Code == "R001" || reportSet.Code == "R015" || reportSet.Code == "R016"
                     || reportSet.Code == "R017"
                      || reportSet.Code == "R018"
                       || reportSet.Code == "R019"
                        || reportSet.Code == "R020"
                         || reportSet.Code == "R021"))
                {
                    _CurrentHead.TestVoltage = _CurrentHead.Voltage;
                }
            }
            catch (Exception ex)
            {
                QMessageBox.ShowException1(ex);
            }
        }

        private void btnApiMsg_Click(object sender, EventArgs e)
        {
            FormMutilMsgBox f = new FormMutilMsgBox("FQC接口信息", "", OrtService.FqcApiData);
            f.Show();
        }
    }
}
